发送消息:
static void Main(string[] args) { UdpClient udpClient = new UdpClient(AddressFamily.InterNetwork); IPEndPoint broadcastIp = new IPEndPoint(IPAddress.Broadcast, 4534); int i = 0; while (true) { i++; byte[] b = Encoding.UTF8.GetBytes("我在广播消息" + i); udpClient.Send(b, b.Length, broadcastIp); Console.WriteLine(i); System.Threading.Thread.Sleep(1000); } //udpClient.Close(); //Console.WriteLine("Done"); //Console.Read(); }
接收消息:
static void Main(string[] args) { try { UdpClient receiveUdpClient = new UdpClient(1); IPEndPoint localIP = new IPEndPoint(IPAddress.Any, 0); while (true) { byte[] r = receiveUdpClient.Receive(ref localIP); Console.WriteLine(Encoding.UTF8.GetString(r)); } } catch (Exception ex) { Console.WriteLine(ex.Message + ex.StackTrace); } }