udpClient.Receive 在 MonoDroid 下不接收任何 UDP 数据报模拟器
使用以下代码,我在 MonoDroid + Simulator 下没有收到任何 UDP 数据报。但相同的代码在 MonoTouch 下运行良好...
好吧,我知道不能保证同一段代码在不同平台上的运行类似。但归根结底,这正是我在 iOS 和 Android 上使用 C# 所期望的。
System.Threading.Thread udpListener = new System.Threading.Thread(() =>
{
System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(UDP_PORT);
while (true)
{
try
{
System.Net.IPEndPoint sender = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
byte[] bytes = udpClient.Receive(ref sender);
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyMessageList));
MyMessageList messages = serializer.Deserialize(ms) as MyMessageList;
if (messages != null) ParseNotificationMessages(messages);
}
}
catch (System.Exception exp)
{
}
}
});
udpListener.IsBackground = true;
udpListener.Start();
干杯,帕特里克
With the following bit of code, I doesn't receive any UDP datagram under MonoDroid + Simulator. But the same code works well under MonoTouch...
Ok, I know there are no guaranty that the same piece of code works similarly on different platform. But in the end of the day, it is what I expect from using C# on iOS and Android.
System.Threading.Thread udpListener = new System.Threading.Thread(() =>
{
System.Net.Sockets.UdpClient udpClient = new System.Net.Sockets.UdpClient(UDP_PORT);
while (true)
{
try
{
System.Net.IPEndPoint sender = new System.Net.IPEndPoint(System.Net.IPAddress.Any, 0);
byte[] bytes = udpClient.Receive(ref sender);
using (System.IO.MemoryStream ms = new System.IO.MemoryStream(bytes))
{
System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(MyMessageList));
MyMessageList messages = serializer.Deserialize(ms) as MyMessageList;
if (messages != null) ParseNotificationMessages(messages);
}
}
catch (System.Exception exp)
{
}
}
});
udpListener.IsBackground = true;
udpListener.Start();
Cheers, Patrick
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
奇怪的; UDP应该工作,因为这是我们的测试之一:
现在,上面的代码使用环回设备而不是“真实”设备,但我希望/期望它工作......
什么端口你想阅读吗? Android 确实使用 Linux 内核,因此对小于 1024 的端口的访问仅限于授权用户。
另一种可能是您缺少
android.permission.INTERNET
权限,这是所有与网络相关的操作所必需的。Odd; UDP should work, as this is one of our tests:
Now, the above code uses the loopback device instead of a "real" device, but I would hope/expect it to work...
What port are you trying to read from? Android does use the Linux kernel, so access to ports less than 1024 is restricted to authorized users.
Another possibility is that you're missing the
android.permission.INTERNET
permission, which is required for all network-related operations.