UDP是一个无连接协议,传输数据之前源端和终端不建立连接,当它想传送时就简单地去抓取来自应用程序的数据,并尽可能快地把它扔到网络上。在发送端,UDP传送数据的速度仅仅是受应用程序生成数据的速度、计算机的能力和传输带宽的限制;在接收端,UDP把每个消息段放在队列中,应用程序每次从队列中读一个消息段。
由于传输数据不建立连接,因此也就不需要维护连接状态,包括收发状态等,因此一台服务机可同时向多个客户机传输相同的消息。这样就极大地减少了系统开销,降低了流媒体的误码率和丢包率,并保证了流媒体播放的平滑性
Udp服务端
internal class Program{static void Main(string[] args){// 初始化服务器端本身ip以及端口UdpClient udpListener = new UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234));// 客户端的ip以及端口IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1235);// 发送数据byte[] data;//udpListener.Send(data, data.Length, remoteEndPoint);// 发送消息var taskA = Task.Run(() =>{while (true){try{string readStr = Console.ReadLine();if (!string.IsNullOrWhiteSpace(readStr) && readStr.StartsWith("W:")){data = Encoding.UTF8.GetBytes(readStr.Substring(2));udpListener.Send(data, data.Length, remoteEndPoint);}}catch (Exception ex){return;}}});// 接收消息var taskB = Task.Run(() =>{while (true){// 接收数据byte[] receivedData = udpListener.Receive(ref remoteEndPoint);string receivedMessage = Encoding.UTF8.GetString(receivedData);Console.WriteLine($"Received: {receivedMessage}");}});// 主线程等待任务Task.WaitAll(taskA, taskB);}}
客户端
internal class Program{static void Main(string[] args){// 客户端自身端口System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1235));// 这是服务器ip以及端口IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1234);// 发送消息var taskA = Task.Run(() => {while (true){string readStr = Console.ReadLine();if(!string.IsNullOrWhiteSpace(readStr) && readStr.StartsWith("W:")){byte[] data = Encoding.UTF8.GetBytes(readStr.Substring(2));udpClient.Send(data, data.Length, serverEndPoint);}}});// 接收消息var taskB = Task.Run(() => {while(true){byte[] receivedData = udpClient.Receive(ref serverEndPoint);string receivedMessage = Encoding.UTF8.GetString(receivedData);Console.WriteLine($"Received: {receivedMessage}");}});Task.WaitAll(taskA,taskB);}}