在我的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();
}
调试截图:
第一次收到完整字节:
第二次和字节为空:
这里有什么问题?
答案 0 :(得分:0)
最终我弄明白了。这似乎是由多个线程试图同时收听(请参阅this帖子)回复引起的错误,所以我将发布我的解决方案:
RecieveTimeout
添加了X
UdpClient
秒。 EndRecieve
和Close
方法调用。BeginRecieve
中传递的回调执行,所以如果客户端仍处于打开状态,我会在回调方法中添加一个检查
if (udp.Client != null) ...
它为我修好了东西,所以希望它会帮助别人