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.XmlSerialize开发者_开发问答r 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
Odd; UDP should work, as this is one of our tests:
int Port = 9595;
var server = new UdpClient(Port);
server.BeginReceive(result => {
IPEndPoint sender = null;
var data = server.EndReceive(result, ref sender);
var value = Encoding.Unicode.GetString (data);
if (value != "hello there!")
throw new InvalidOperationException ("UDP data transfer failed!");
RunOnUiThread (() => textview.Text += "\n\nRead data from UDP: " + value);
server.Close ();
}, null);
using (var client = new UdpClient()) {
var bytes = Encoding.Unicode.GetBytes("hello there!");
client.Send(
bytes,
bytes.Length,
new IPEndPoint(IPAddress.Loopback, Port));
}
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.
精彩评论