// -------------------- Receive -------------------- \\ private void ReceiveCallback(IAsyncResult ar) { // Read incoming data from the client. if (_isDisposed) { Console.WriteLine($"Ignored incoming message as this object is disposed."); return; } int bytesRead = 0; try { bytesRead = _socket.EndReceive(ar); } catch (SocketException e) { OnDisconnect(e); return; } if (bytesRead > 0) { // Parse the message lock (_parsingMessageLock) { try { byte[] b = (byte[])ar.AsyncState; _packetProtocol.DataReceived(b, bytesRead); } catch (ProtocolViolationException e) { Console.WriteLine("Failed to receive data. Package protocol violation. \n" + e.ToString()); _packetProtocol.MessageArrived = null; _packetProtocol.KeepAliveArrived = null; _packetProtocol = new PacketProtocol <TMessageType>(_bufferSize); _packetProtocol.MessageArrived = (MessageType, data) => OnMessageReceived(MessageType, data); } } // Start receiving more data byte[] buffer = new byte[_bufferSize]; _socket.BeginReceive(buffer, 0, _bufferSize, 0, new AsyncCallback(ReceiveCallback), buffer); } }