Question

So I'm writing a program in C# where a server is sending me (the client) UDP datagrams constantly. 1 datagram would translate to a 1 line message. Currently I am constantly calling the Recieve method in an infinite loop like so:

IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
while (true)
{
     Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);
     returnData = Encoding.ASCII.GetString(receiveBytes);
}

I call another method in the loop to work with the returnData in another thread. But is this the correct way to recieve the constant stream that is being sent to me? I've noticed that the frequency of messages I'm receiving is different from the frequency set by the actual server to send. Thanks for the help!

Cheers.

Était-ce utile?

La solution

UDP is connectionless oriented protocol, that means that the packets received may not be in the order they were sent; also packets may be lost without any information or hints of that fact. If you need to make sure you receive all packets you have 2 main options:

  1. TCP: Use TCP as the protocol to use, if the connection is one (server) to one (client) then it's a better choice. TCP offers all the necessary security, CRC and hand-shake to keep the data integrity, it is like a stream and when no more data could be sent it blocks the sender side until the reader side reads the buffered data.

  2. UDP: is better suited when more than one sender is sending data to the receiver thru the same port. If packets integrity is crucial then the receiver should send an ACK (acknowledge) packet for every packet received to the sender, if the sender does not receive the ACK packet in a reasonable time then it should resend the packet until the appropriate ACK is received.

    If the reception of UDP packets is done in a separate thread, increase this thread's priority, it's the most important one, set it to "Time-Critical priority", otherwise, decrease the thread that process the data received, put it in "Below-Normal priority". Finally, you say that you "call another method in the loop with the received data", I think there must something wrong with this, you should put the data in a Queue and the process thread would pick it up, but DON'T CALL the method within the reception, and, of course, DO NOT CREATE a thread every time you receive a packet.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top