Please tell me how to split a UDP socket into threads so that the server can simultaneously receive data from ten clients on one port?

UPD :

enter image description here

UPD2 :

Client :

// Конструктор клиента UdpClient udpClient = new UdpClient(11001); udpClient.Connect("127.0.0.1", 11000); repeat: // Тут мы отправляем "типа" данные byte[] sendBytes = Encoding.UTF8.GetBytes("Привет :D"); for (int i = 0; i < new Random().Next(100); i++) { udpClient.Send(sendBytes, sendBytes.Length); } //Это я не знаю для чего, но без него программа не работает ) IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); // А это мы получаем сообщение от клиента (Ну если условно, то сервера) Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint); string returnData = Encoding.UTF8.GetString(receiveBytes); if (returnData == "Давай по новой") { goto repeat; } // Разрываем соединение. udpClient.Close(); 

Server :

 async void RegisterTask(Task task) { try { activeTasks.Add(task); await task; } finally { activeTasks.Remove(task); } } const int listenPort = 11000; UdpClient listener = new UdpClient(listenPort); private async void button_Click(object sender, RoutedEventArgs e) { while (true) { var result = await listener.ReceiveAsync(); Console.WriteLine($"Received from {result.RemoteEndPoint} {result.Buffer.Length} bytes"); string returnData = Encoding.UTF8.GetString(result.Buffer); // если ваша обработка длительная, то стартуйте Task, обрабатывающий данные, здесь Task processTask = Process(result); RegisterTask(processTask); } } private Task Process(UdpReceiveResult result) { IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0); Byte[] receiveBytes = listener.Receive(ref RemoteIpEndPoint); string returnData = Encoding.UTF8.GetString(receiveBytes); listener.Send(Encoding.UTF8.GetBytes("Давай по новой"), Encoding.UTF8.GetBytes("Давай по новой").Length); return null; } 
  • Is it And the threads are not needed, you need async / await. - VladD
  • Okay. Why not UdpClient ? UDP, if I'm not mistaken, does not require a connection, so there is essentially no difference between the client and the server. - VladD
  • @PavelMayorov: Well, RemoteEndPoint comes to it, and distinguish it by it. - VladD
  • @PavelMayorov: In my code, it is issued to the console - VladD
  • No need to insert large pictures - they are difficult to look at and search for them does not work. - Pavel Mayorov

1 answer 1

Update : Corrected the code to fit your case more.

 const int listenPort = 11000; using (UdpClient listener = new UdpClient(listenPort)) { while (true) { var result = await listener.ReceiveAsync(); Console.WriteLine( $"Received from {result.RemoteEndPoint} {result.Buffer.Length} bytes"); // если ваша обработка длительная, то стартуйте Task, обрабатывающий данные, здесь Task processTask = Process(result); } } async Task Process(UdpReceiveResult result) { var endpoint = result.RemoteEndPoint; byte[] message = result.Buffer; using (var sender = new UdpClient()) { sender.Connect(endpoint.Address, destinationPort); var backMessage = Encoding.UTF8.GetBytes("Давай по новой"); await sender.SendAsync(backMessage, backMessage.Length); } } 
  • Comments are not intended for extended discussion; conversation moved to chat . - Nick Volynkin