private void ReceiveCallback(IAsyncResult ar) { try { Debug.Log("Receive callback "); // Retrieve the state object and the client socket // from the asynchronous state object. StateObject state = (StateObject)ar.AsyncState; System.Net.Sockets.Socket client = state.workSocket; // Read data from the remote device. int bytesRead = client.EndReceive(ar); Debug.Log("bytes read: " + bytesRead.ToString()); if (bytesRead > 0) { if (state.expected == -1) { state.expected = PacketUtils.GetSizeFromOpCodeReceived((OpCodeReceive)state.buffer[0]); } state.offset += bytesRead; Debug.Log("state offset: " + state.offset.ToString()); // Get the rest of the data. if (state.offset < state.expected) { Debug.Log("State.buffer = " + state.buffer.Length.ToString()); Debug.Log("State.offset = " + state.offset.ToString()); Debug.Log("StateObject.Buffersize = " + StateObject.BufferSize.ToString()); client.BeginReceive(state.buffer, state.offset, StateObject.BufferSize - state.offset, 0, new AsyncCallback(ReceiveCallback), state); Debug.Log("lesser than expected"); } else if (state.offset == state.expected) { finishRead(state); } else { Debug.Log("Too many packets arrived"); } } else { // All the data has arrived; put it in response. if (state.offset == state.expected) { finishRead(state); } else { Receive(client); } // Signal that all bytes have been received. // receiveDone.Set(); } } catch (Exception e) { Debug.Log(e.ToString()); } }