一.服务器端
1.声明一个套接字
static Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
2.绑定一个IP和端口号
udpServer.Bind(new IPEndPoint(new IPAddress(new byte[] { 192, 168, 0, 100 }), 7788));
//每进入一个用户,就为他声明一个死循环的接收数据的进程
new Thread(ReceiveMessage) { IsBackground = true }.Start();
Console.ReadKey();
3.收发数据
//UDP随机挑选一个端口进行发送数据,端口是随机的
static void ReceiveMessage()
{
while (true)
{
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0);
byte[] data = new byte[1024];
//这个方法会把数据的来源放到第二个参数上
int length = udpServer.ReceiveFrom(data, ref remoteEndPoint);
string message = Encoding.UTF8.GetString(data, 0, length);
Console.WriteLine("从ip" + (remoteEndPoint as IPEndPoint).Address.ToString() + " 端口:" + (remoteEndPoint as IPEndPoint).Port.ToString() + "得到数据" + message);
}
}
二.客户端
class Program
{
//1.声明一个套接字
static Socket udpserver = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
static void Main(string[] args)
{
SendMessage();
Console.ReadKey();
}
static void SendMessage()
{
//2.声明一个端口号
EndPoint endPoint = new IPEndPoint(IPAddress.Parse("192.168.0.100"), 7788);
while (true)
{
string message = Console.ReadLine();
byte[] data = Encoding.UTF8.GetBytes(message);
udpserver.SendTo(data, endPoint);
}
}
}