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

时间:2015-03-14 20:06:34

标签: c# android xamarin xamarin.android

在我的Xamarin.Android应用中,我发送udp广播消息以在本地LAN上查找我的服务器。 然后我的服务器返回它们运行的​​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();
}

调试截图:

第一次收到完整字节: First time

第二次和字节为空: Second time and on

这里有什么问题?

1 个答案:

答案 0 :(得分:0)

最终我弄明白了。这似乎是由多个线程试图同时收听(请参阅this帖子)回复引起的错误,所以我将发布我的解决方案:

  1. 我向RecieveTimeout添加了X UdpClient秒。
  2. 超时后,我执行EndRecieveClose方法调用。
  3. 这将触发BeginRecieve中传递的回调执行,所以如果客户端仍处于打开状态,我会在回调方法中添加一个检查 if (udp.Client != null) ...
  4. 它为我修好了东西,所以希望它会帮助别人