public async Task ReadLoop(TcpClient client) { var delimiter = _tcpServer.Delimiter; var queuedMsg = new List <byte>(); while (!_cancellationToken.IsCancellationRequested) { if (!IsSocketConnected(client.Client)) { _tcpServer.FireClientDisconnected(_tcpServer, client); client.GetStream().Close(); client.Close(); break; } var bytesAvailable = client.Available; if (bytesAvailable == 0) { continue; } var bytesReceived = new List <byte>(); while (client.Available > 0 && client.Connected) { var nextByte = new byte[1]; await client.GetStream().ReadAsync(nextByte, 0, 1, _cancellationToken.Token); bytesReceived.AddRange(nextByte); if (nextByte[0] == delimiter) { var msg = Encoding.ASCII.GetString(queuedMsg.ToArray()); _tcpServer.FireMessageReceived(_tcpServer, client, msg); queuedMsg.Clear(); bytesReceived.Clear(); } else { queuedMsg.AddRange(nextByte); } } if (bytesReceived.Count > 0) { var msg = Encoding.ASCII.GetString(queuedMsg.ToArray()); _tcpServer.FireMessageReceived(_tcpServer, client, msg); } } }