Unity Freezes while waiting for data

I’m working on my own stand-alone server, which I’ve gotten doing what I want it doing through Console client, however now that I’m trying to transfer the client over to unity, I’m having some problems, this problem is that when I want to receive data, the client freezes until that data is received, so unless the server is constantly polling, the client is just useless, completely frozen until I shut the server off.

	void Update () 
	{
		if(clientSocket.Receive(new Byte[1024]) < 1)
			return;
		recieve = clientSocket.Receive(new Byte[1024]);
	}

I attempted using the If statement to tell it to return if the bytes received was empty, however that didn’t work.

the line

recieve = clientSocket.Receive(new Byte[1024]);

is what is causing the problems…

I guess I’m not really sure how exactly to handle this inside of unity, honestly. Any help would be appreciated.

Use a coroutine

exactly,
coroutine will do the job, since data is not being sent async, so unity waits until data is received hence the freezing.

Look into BeginReceive and BeginSend which are asynchronous methods. Unity will crash because you are using Blocking Sockets which will halt the thread that they were created on (In your case this is the main Unity thread) and the entire client will wait until data is received.

Co-routine wont work, since the .Receive call is blocking and co-routines execute on the main thread.

However, something like this would work (UDP socket):

public class SocketBehaviour : MonoBehaviour {

    Socket socket;
    byte[] buffer = new byte[1024];

    void Start () {
        socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        socket.Bind(new IPEndPoint(IPAddress.Any, 0));
        socket.Blocking = false;

        StartCoroutine(Poll());
    }

    IEnumerator Poll () {
        while (true) {
            yield return null;
            if (socket.Poll(0, SelectMode.SelectRead)) {
                int bytesReceived = socket.Receive(buffer, 0, buffer.Length, SocketFlags.None);

                if (bytesReceived > 0) {
                    // process data
                }
            }
        }
    }
}
2 Likes