TCP维持起来比较复杂,相对来说,UDP就简单很多了,正好有一个东西需要传递一些信息,就又学习了一下UDP
首先需要建立一个UDP的接收端,尽量化简,有什么问题再说吧
代码很简单
int listenPort = 4567; ipEndPoint = new IPEndPoint(IPAddress.Any, listenPort); udpReceive = new UdpClient(ipEndPoint); IAsyncResult iar = udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceive);
接收回调
private void ReceiveCallback(IAsyncResult iar) { UdpClient udpReceive = iar.AsyncState as UdpClient; Byte[] receiveBytes = udpReceive.EndReceive(iar, ref ipEndPoint); string receiveString = Encoding.Default.GetString(receiveBytes); udpReceive.BeginReceive(new AsyncCallback(ReceiveCallback), udpReceive); }