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?
source share