Coroutine Freezing

Hi there, I’m having some trouble understanding why this coroutine is causing my game to freeze until i shut down my server or otherwise forcibly close the connection from the remote host. Any help would be much appreciated.

public IEnumerator SocketCoroutine(Socket socket) {
     byte[] buffer;
     int readBytes = 0;

     for (;;) {
         buffer = new byte[socket.SendBufferSize];
         yield return readBytes = socket.Receive(buffer);

         if (readBytes > 0) {
             Packet packet = new Packet(buffer);
             Client.HandlePacket(packet);
         }
     }
}

I’m not too familiar with using a For loop in that manner. Wouldn’t that be endless?

Not sure about your assignation and then yielding of the readBytes integer. It may be right, but I’ve never seen that construct.

Generally you create a socket and yield on it, then inspect it for results.

Also, to keep the crashing down a bit while you debug your true intentions, try sticking another yield inside the for loop:

yield return null;

Right at the top, before buffer is allocated.

Socket.Recieve is blocking if there is insufficient data to fill the byte array. From MSDN.

Since your byte array is the full size of the buffer, this makes sense. You probably want to use the available property to set the byte array size, and cut out if the availability is zero.

You also want to yield null to wait a frame. Yielding an int really does nothing, and just confuses your code.

You should also use while (true) instead of an empty for loop. Say what you mean, it’s easier for everyone.

Like so:

public IEnumerator SocketCoroutine(Socket socket) {
     byte[] buffer;
     int readBytes = 0;

     while (true) {
         while (socket.Available <= 0) yield return null;
         buffer = new byte[socket.Available];
         readBytes = socket.Receive(buffer);
         Packet packet = new Packet(buffer);
         Client.HandlePacket(packet);
     }
}
1 Like

@Kiwasi
Thanks, I think im miss understanding what yield does, I thought it waited untill an instruction had been carried out. Ive changed my code to match yours and it works perfectly, Thank you.

@absolute_disgrace
yeah its an infinite loop, effectively does the same as while (true).

1 Like