Udp 第一次读取空字节 - mono android

Udp reads empty bytes after first time - mono android

在我的 Xamarin.Android 应用程序上,我正在发送 udp 广播消息以在本地 LAN 上查找我的服务器。 然后我的服务器 return 他们 运行 的 MachineName 我以

的形式在我的应用程序的 ListView 中显示

<MachineName> - <Ip address>

第一次一切正常,但是从第二次开始,它读取的都是空字节。 它读取的字节数是正确的,但它们都是零。

代码如下:

private static void ListenForBroadcastResponses()
{
    udp.BeginReceive(OnBroadcastResponse, new object());
}

private static void OnBroadcastResponse(IAsyncResult ar)
{
    // Recieve the message
    IPEndPoint ip = new IPEndPoint(IPAddress.Any, port);
    byte[] bytes = udp.EndReceive(ar, ref ip);
    // Decode it
    string message = Encoding.ASCII.GetString(bytes);
    // If message is the awaited message from client or from the awaited port
    if (ip.Port == port) //|| message == BRDCAST_ANSWER)
    {
        // Raise server found event
        var handler = ServerFound;
        if (handler != null)
            handler(null, new ServerEventArgs
            {
                Server = new Server(message, ip.Address)
            });
    }

    // Start listening again
    ListenForBroadcastResponses();
}

调试截图:

第一次收到完整字节:

第二次和on字节为空:

这里有什么问题?

我终于明白了。这似乎是一个错误,由多个线程试图同时监听(参见 this post)回复,所以我将 post 我的解决方案:

  1. 我在 UdpClient 的基础上增加了 RecieveTimeout X 秒。
  2. 超时后,我执行 EndRecieveClose 方法调用。
  3. 这将触发传入 BeginRecieve 的回调执行,因此如果客户端仍处于打开状态,我会在回调方法中添加一个检查 if (udp.Client != null) ...

它为我解决了一些问题,希望它能帮助其他人