C#实现简单的udp收发的代码
发送
try { Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); //向此网段发广播包 int UDPListenerPort = 8082; IPAddress broadcast = IPAddress.Parse("192.168.0.255"); //此处根据IP及子网掩码改为相应的广播IP string ts = "This is UPD string for sending"; byte[] sendbuf = Encoding.ASCII.GetBytes(ts); IPEndPoint ep = new IPEndPoint(broadcast, UDPListenerPort); s.SendTo(sendbuf, ep); } catch (Exception e) {}
接收
UdpClient listener; int UDPListenerPort = 8082; IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, UDPListenerPort); try { while (true) { byte[] bytes = listener.Receive(ref groupEP); string RecIP = groupEP.ToString().Substring(0, groupEP.ToString().IndexOf(":")); //收到发送UPD端的IP string RecStr = Encoding.ASCII.GetString(bytes, 0, bytes.Length); //收到的UPD字符串 } } catch {}