Omribitan Omribitan - 4 months ago 22
Android Question

Udp reads empty bytes after first time - mono android

On my

app I'm sending udp broadcast message to find my servers on the local LAN.
My servers then return the MachineName they run on which I display in a ListView on my app in the form of

<MachineName> - <Ip address>

This all works well on the first time, however from the second time on all it reads is empty bytes.
The number of bytes it reads is correct but they are all zero.

Here is the code:

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

Debug screenshots:

First time full bytes are recieved:
First time

Second time and on bytes are empty:
Second time and on

What is wrong here?


Eventually I figured it out. It seems to be a bug caused by multiple threads trying to listen simultaneously (see this post) to replies so I'll post my solution:

  1. I've added a RecieveTimeout of X seconds to the UdpClient.
  2. Upon timeout, I execute an EndRecieve and Close method calls.
  3. This will trigger the callback passed in BeginRecieve to execute so I've added a check to the callback method if the client is still open if (udp.Client != null) ...

It fixed things for me, so hopefully it will help others