static async Task HandleTcpClient(TcpClient client) { var stream = client.GetStream(); var buffer = ArrayPool <byte> .Shared.Rent(12); try { while (true) { int read = 0; do { int r = await stream.ReadAsync(buffer.AsMemory(read, 12 - read)); if (r <= 0) { Console.WriteLine("Connection to {0} closed", client.Client.RemoteEndPoint); client.Close(); return; } else { read += r; } }while (read < 12); _Stats.NewMessageReceived(12); WriteResponseToBuffer(buffer); await stream.WriteAsync(buffer.AsMemory(0, 8)); _Stats.NewMessageSent(8); } } catch (Exception ex) { Console.WriteLine("IO Exception caught: {0}; closing client connection", ex.Message); client.Close(); } finally { ArrayPool <byte> .Shared.Return(buffer); }