简体   繁体   English

C#Udp BeginReceive-消息混乱

[英]c# Udp BeginReceive - Messages out of order

I'm currently trying to create an UDP client/server. 我目前正在尝试创建UDP客户端/服务器。 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. SendAndReceive函数使用10秒计时器。

EDIT: If I recreate MyUdpClient each time I call the SendAndReceive function it works and the packages are not in the wrong order. 编辑:如果我每次调用SendAndReceive函数时都重新创建MyUdpClient,则它将正常工作,并且程序包的顺序不正确。

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 a Task instead of .BeginReceive . 我改变了我的整个实现使用.ReceiveTask ,而不是.BeginReceive I found using a Task to be better because I needed to safely stop the and start the receive function and it fixed the weird issue I had. 我发现使用Task会更好,因为我需要安全地停止并启动接收功能,并且它解决了我遇到的怪异问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM