开发者

udpClient.Receive doesn't receive any UDP datagram under MonoDroid + Simulator [duplicate]

开发者 https://www.devze.com 2023-04-04 07:48 出处:网络
This question already has answers here: How to receive data using UDP in Android? (2 answers) Closed 2 years ago.
This question already has answers here: How to receive data using UDP in Android? (2 answers) Closed 2 years ago.

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号