基于C#的UDP协议消息传输
1. 服务端
internal class Program
{
static void Main(string[] args)
{
//1.创建Socket
Socket socketServer =new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
//2.绑定IP、端口号
EndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5566);
socketServer.Bind(endPoint);
//3.接收消息
byte[] buffer = new byte[1024];
EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
int length = socketServer.ReceiveFrom(buffer, ref remoteEP);
Console.WriteLine(Encoding.UTF8.GetString(buffer, 0, length));
socketServer.Close();
Console.ReadLine();
}
}
2.客户端
internal class Program
{
static void Main(string[] args)
{
// 创建Socket
Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
// 目标IP和端口号
EndPoint endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5566);
// 发送消息
string message = "Hello, Server!";
byte[] buffer = Encoding.UTF8.GetBytes(message);
socketClient.SendTo(buffer, endPoint);
Console.WriteLine("消息已发送");
socketClient.Close();
Console.ReadLine();
}
}
3.执行
先启动服务端exe,再启动客户端exe,客户端会向服务端发送消息。