I'm currently trying to create an UDP client/server. It's quite simple, there's a send function which sends a byte and then the clients immediately respond with an message containing information which I listen for
I've been having trouble with receiving data. I receive data all the time and the packages received do have the correct length, however the messages seem to be out of order.
The SendAndReceive function is on an 10 seconds timer.
EDIT: If I recreate MyUdpClient each time I call the SendAndReceive function it works and the packages are not in the wrong order.
Heres my code:
private void SendAndReceive(object sender = null, ElapsedEventArgs e = null)
{
ClientEndpoint = new IPEndPoint(IPAddress.Parse(IP), Port);
// Works if i recreate MyUdpClient...
MyUdpClient = new UdpClient();
MyUdpClient.ExclusiveAddressUse = false;
MyUdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
MyUdpClient.Send(InfoPacket, InfoPacket.Length, ClientEndpoint);
try
{
MyUdpClient.BeginReceive(new AsyncCallback(ReceiveMessages), null);
}
catch (Exception exception)
{
Console.WriteLine($"Exception: {exception.ToString()}");
}
}
public void ReceiveMessages(IAsyncResult res)
{
IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, Port);
byte[] receivedPacket = MyUdpClient.EndReceive(res, ref RemoteIpEndPoint);
var ipAddress = RemoteIpEndPoint.Address.ToString();
MyUdpClient.BeginReceive(new AsyncCallback(ReceiveMessages), null);
// This is for debugging.
string receivedTime = DateTime.Now.ToString("HH:mm:ss");
Console.WriteLine($"[{receivedTime}]{ipAddress} {receivedPacket.Length} {Encoding.Default.GetString(receivedPacket)}");
// Process Data Further
...
}
The common output is usually something like this:
[18.29.30]172.20.55.32 475 a
[18.29.30]172.20.55.10 455 b
[18.29.30]172.20.55.101 440 c
[18.29.30]172.20.55.17 452 d
[18.29.30]172.20.55.31 414 e
[18.29.30]172.20.55.20 449 f
[18.29.30]172.20.55.8 456 g
[18.29.30]172.20.55.28 381 h
...
[18.29.40]172.20.55.32 475 a
[18.29.40]172.20.55.10 455 b
[18.29.40]172.20.55.101 440 c
[18.29.40]172.20.55.17 452 d
[18.29.40]172.20.55.31 414 c <-- (gets cut down to 414 bytes)
[18.29.40]172.20.55.20 449 f
[18.29.40]172.20.55.8 456 g
[18.29.40]172.20.55.28 381 h
The letters represent the decoded messages. The first time receiving these messages they are correct, however after that, the messages gets messed up.
Any ideas? I'm not sure what direction to take. Is it a threading issue or do I have to decode the received packages at a later time?
Thanks for any help and/or guidance
-André
I changed my whole implementation to use
.Receive
in aTask
instead of.BeginReceive
. I found using aTask
to be better because I needed to safely stop the and start the receive function and it fixed the weird issue I had.