Net Core教程

C# UDP同步获取消息

本文主要是介绍C# UDP同步获取消息,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

 

 1  private void Listening(int port, CancellationTokenSource cts)
 2         {
 3             cts.Token.ThrowIfCancellationRequested();
 4 
 5             Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
 6             server.ReceiveBufferSize = UInt16.MaxValue * 8;
 7             server.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
 8             IPAddress ip = IPAddress.Any;
 9             server.Bind(new IPEndPoint(ip, port));
10 
11             Console.WriteLine("------ReceiveMessage--");
12             while (true)
13             {
14                 if (cts.IsCancellationRequested)
15                 {
16                     cts.Token.ThrowIfCancellationRequested();
17                 }
18                 byte[] data = new byte[1024 * 8];
19                 EndPoint endPoint = new IPEndPoint(IPAddress.Any, 0);
20                 int count = server.ReceiveFrom(data, ref endPoint);
21                 if (count > 0)
22                 {
23                     string message = Encoding.UTF8.GetString(data);
24                     Console.WriteLine(message);
25                 }
26             }
27         }

 

这篇关于C# UDP同步获取消息的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!