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 }