Unity UDP freezes if disconnected from server

Here is the code :

private String sendString(string message)
	{
		try
		{
			//if (message != "")
			//{

			//Sending data to client--->
			byte[] data = Encoding.UTF8.GetBytes(message);
			int re = client.Send(data, data.Length, remoteEndPoint);
			//Receiving data from client--->
			byte[] recv = client.Receive(ref remoteEndPoint);
			//Debug.Log("Received from " + remoteEndPoint.Address.ToString());
			String result = System.Text.Encoding.UTF8.GetString(recv);
			//Debug.Log (result + " " + remoteEndPoint.Address.ToString());

			return result;
			//}
		}
		catch (Exception err)
		{
			print(err.ToString());
			return "false";
		}
	}

This works fine as long as the app is connected to the server. But as soon as it is disconnected from the server, the game freezes.
Can someone please help with this?

EDIT: I have found out that client.Receive causes the problem. Because as soon as I remove the receive part, it does not freeze even after the client is disconnected.

Hello @nikrath

UDP doesn’t make connections. The remote host is reachable or not.
When you call client.Receive() you’re blocking the current thread while it waits to get a message on the UDP port. Because the thread is blocked, Unity is starved and can’t make updates - so it freezes.

You need to call Select() before doing the receive to check if any data is available on the port, then read the port if there is - this is the basis for non-blocking I/O.

You could try doing the read in another thread but that’s also not great because that thread will block - unless you do Select() first - and that just causes things to come to a grind.

Hope that helps.

Regards
Warwick

Perhaps you can use this :

To disable your Receiver.

I’d try to make a class variable bool canReceive and make it false in the OnDisconnectedFromServer callback. Then simply wrap your receive statement with it

if(canReceive)
{
    byte[] recv = client.Receive(ref remoteEndPoint);
}

This should hopefully skip the freeze on disconnect.