C # UDP server with multiple users

Consider the code:

class UPDServer { //start listener public void start() { UdpClient listener = new UdpClient(this._porta); IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Any, 10000); State s = new State(); s.listener = listener; s.ipEndPoint = ipEndPoint; // begin to listen again listener.BeginReceive(new AsyncCallback(ReceiveCallback), s); } //receive data public void ReceiveCallback(IAsyncResult ar) { // we got data State s = (State)(ar.AsyncState); Byte[] received = e.escuta.EndReceive(ar, ref e.ipEndPoint); string text = ""; = Encoding.ASCII.GetString(received); // ... do somenthing with text // begin to listen again s.listener.BeginReceive(new AsyncCallback(ReceiveCallback), e); } } 

In the above code, there is a period of time between EndReceive and the next BeginReceive that no one is listening to, I think that if there is a message at this time, it will be lost.

Well, I suppose there is some kind of buffer o, but even if the buffer fills up in a period of time when no one is listening to messages, the messages will be lost.

I remember someone saying that this can be solved very simply by calling BeginReceive on the same endpoint several times, so I tried this:

  for( int x = 0; x < 5;x++) { escuta.BeginReceive(new AsyncCallback(ReceiveCallback), e); } 

The extremely triggering start of reception on the same socket does not cause errors, but every time a message arrives, all five of the beginReceive operations and all five receive the same message.

Is there a way to improve the code?

+4
source share
1 answer

Firstly, there is no guarantee that you will receive all your data when using UDP, so you must make your code / protocol fault-tolerant independently.

If your processing is not very intensive, and you expect a huge amount of data to get into the stream, you probably do not need to do something different. Just add an error code so you know if your code is coping.

However, if you need to quickly maintain a receive cycle when you receive data, copy it to the queue to process another stream so that you can quickly start reading. Or in some cases, you can write your end-of-reception so that it can handle the forwarding if multiple packets come back.

+2
source

Source: https://habr.com/ru/post/1411824/


All Articles