服务端代码
static void Main(string[] args)
{
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8090));
EndPoint clientPoint= new IPEndPoint(IPAddress.Any, 0); // 声明一个空的端口对象,当接受到数据的时候,会将数据发送方的地址赋值到该对象中
byte[] reciveData = new byte[1024];
int dataLength = server.ReceiveFrom(reciveData, ref clientPoint); //接收到连接,会将连接方的地址写入clientPoint
string reciveMessage = Encoding.UTF8.GetString(reciveData, 0, dataLength);
Console.WriteLine(reciveMessage);
server.Close();
Console.ReadKey();
}
客户端代码
static void Main(string[] args)
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
string userMessage = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(userMessage);
EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("192.168.1.255"), 8090);
clientSocket.SendTo(data, serverPoint);
Console.ReadKey();
}