private void TryProcessMessage(MqttClientConnection clientConnection, SocketAsyncEventArgs receiveSendEventArgs) { int lastProcessedByteByCompleteMessage = -1; int remainingBytesToProcess = clientConnection.PreviouslyReceivedBytes + receiveSendEventArgs.BytesTransferred; var bufferOffset = clientConnection.ReceiveSocketOffset; while (remainingBytesToProcess > 0) { try { var messageType = GetMessageType(receiveSendEventArgs.Buffer, ref bufferOffset, ref remainingBytesToProcess); var payloadLength = GetPayloadLength(receiveSendEventArgs.Buffer, ref bufferOffset, ref remainingBytesToProcess); if (payloadLength <= remainingBytesToProcess) { var rawMessage = rawMessageManager.GetRawMessageWithData(clientConnection, messageType, receiveSendEventArgs.Buffer, bufferOffset, payloadLength); clientConnection.EnqueueRawMessage(rawMessage); bufferOffset += payloadLength; remainingBytesToProcess -= payloadLength; lastProcessedByteByCompleteMessage = bufferOffset - clientConnection.ReceiveSocketOffset; } else { throw new AggregateException(); } } catch (AggregateException) { var unprocessedStart = lastProcessedByteByCompleteMessage + 1; var totalUnprocessedBytes = (clientConnection.PreviouslyReceivedBytes + receiveSendEventArgs.BytesTransferred) - unprocessedStart; if (lastProcessedByteByCompleteMessage > 0) { Buffer.BlockCopy(receiveSendEventArgs.Buffer, clientConnection.ReceiveSocketOffset + unprocessedStart, receiveSendEventArgs.Buffer, clientConnection.ReceiveSocketOffset, totalUnprocessedBytes); } receiveSendEventArgs.SetBuffer(clientConnection.ReceiveSocketOffset + totalUnprocessedBytes, clientConnection.ReceiveSocketBufferSize - totalUnprocessedBytes); clientConnection.PreviouslyReceivedBytes = totalUnprocessedBytes; return; } } receiveSendEventArgs.SetBuffer(clientConnection.ReceiveSocketOffset, clientConnection.ReceiveSocketBufferSize); }