使用UDP可以实现局域网内的广播通信,基于广播功能可以做到无服务器,自发现用户。
UDP监听核心代码:
using (UdpClient client = new UdpClient(new IPEndPoint(IPAddress.Any, Port))) { IPEndPoint endpoint = new IPEndPoint(IPAddress.Any, 0); while (true) { Thread.Sleep(10); if (client.Client.Available <= 0)//可防止报错 { continue; } byte[] buf = client.Receive(ref endpoint); string msg = Encoding.Default.GetString(buf); MsgParse(endpoint, msg); } }
UDP消息广播核心代码:
sendClient = new UdpClient(new IPEndPoint(IPAddress.Any, 0)); byte[] buf = Encoding.Default.GetBytes(str); IPEndPoint endpoint = new IPEndPoint(IPAddress.Parse("255.255.255.255"), Port); sendClient.Send(buf, buf.Length, endpoint);
效果如下图:
下载源码:
https://files.cnblogs.com/files/zjfree/ZUdpChat.zip?t=1697011824&download=true
欢迎转载,转载请注明:转载自[ http://www.cnblogs.com/zjfree/ ]