c#Udp BeginReceive - 无序消息

时间:2018-05-02 16:59:29

标签: c# udp beginreceive

我目前正在尝试创建UDP客户端/服务器。这很简单,有一个send函数发送一个字节,然后客户端立即响应一条包含我收听的信息的消息

我一直无法接收数据。我一直收到数据,收到的包确实有正确的长度,但邮件似乎没有问题。

SendAndReceive功能是10秒计时器。

编辑:如果我每次调用SendAndReceive函数时都重新创建MyUdpClient,它就可以运行,而且包的顺序不正确。

继承我的代码:

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
    ...
}

常见输出通常是这样的:

[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

字母代表解码的消息。第一次接收这些消息时,它们是正确的,但在此之后,消息会搞砸。

有什么想法吗?我不确定要采取什么方向。这是一个线程问题,还是我必须在以后解码收到的包?

感谢您提供任何帮助和/或指导

-André

1 个答案:

答案 0 :(得分:0)

我将整个实现更改为在.Receive中使用Task而不是.BeginReceive。我发现使用Task会更好,因为我需要安全地停止并启动接收功能,并且它可以解决我遇到的怪异问题。