Skip to content

Instantly share code, notes, and snippets.

@Tunied
Created May 1, 2022 04:47
Show Gist options
  • Save Tunied/24718cb90f40a7a01590a7355b35de56 to your computer and use it in GitHub Desktop.
Save Tunied/24718cb90f40a7a01590a7355b35de56 to your computer and use it in GitHub Desktop.
向某个端口发送UDP消息
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Sirenix.OdinInspector;
using UnityEngine;
namespace Code.Dev.Network
{
public class Test_UDP_Send : MonoBehaviour
{
public string overrideIP;
public int port; // define in init
public string strMessage = "AA";
public string hostName;
[Button("Send IP", ButtonSizes.Large)]
private void SendStringIP()
{
try
{
var remoteEndPoint = new IPEndPoint(IPAddress.Parse(overrideIP), port);
var client = new UdpClient();
byte[] data = Encoding.UTF8.GetBytes(strMessage);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
print(err.ToString());
}
}
[Button("Send 域名", ButtonSizes.Large)]
private void SendString()
{
try
{
var remoteEndPoint = GetIPEndPointFromHostName(hostName, port, true);
var client = new UdpClient();
byte[] data = Encoding.UTF8.GetBytes(strMessage);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
print(err.ToString());
}
}
[Button("Local Test", ButtonSizes.Large)]
private void SendLocalString()
{
try
{
var remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 7777);
var client = new UdpClient();
byte[] data = Encoding.UTF8.GetBytes("LocalTest->" + strMessage);
client.Send(data, data.Length, remoteEndPoint);
}
catch (Exception err)
{
print(err.ToString());
}
}
public static IPEndPoint GetIPEndPointFromHostName(string hostName, int port, bool throwIfMoreThanOneIP)
{
var addresses = System.Net.Dns.GetHostAddresses(hostName);
if (addresses.Length == 0)
{
throw new ArgumentException(
"Unable to retrieve address from specified host name.",
"hostName"
);
}
else if (throwIfMoreThanOneIP && addresses.Length > 1)
{
throw new ArgumentException(
"There is more that one IP address to the specified host.",
"hostName"
);
}
Debug.Log($"Host {hostName} IP is {addresses[0]}");
return new IPEndPoint(addresses[0], port); // Port gets validated here.
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment