private void StartListener() { var server = new AsyncNetworkStream(_listener.Accept()); HandshakeMessage handshake = server.ReceiveHandshake().Result; server.SendHandshake(HubId.Generate()); using (var buffer = new PooledMemoryStream()) { while (true) { buffer.Reset(); Receive(server, buffer, WireHeader.Size); buffer.Position = 0; WireHeader header = WireHeader.ReadFrom(buffer); //Console.WriteLine($"Received {header.MessageHeader} ({header.PayloadSize.Value.ToString(CultureInfo.InvariantCulture)})"); Receive(server, buffer, header.PayloadSize.Value); _serverReceived++; if (_serverReceived == _count + 1) { _allMessagesReceived.Set(); } } } }
public async ValueTask WriteAsync(Message message, CancellationToken cancellation) { _logger.LogDebug($"Writing header {message.Header.ToString()}"); var wireHeader = new WireHeader(message.Header, new PayloadSize((int)message.Payload.Length)); byte[] buffer = ArrayPool <byte> .Shared.Rent(WireHeader.Size); WireHeader.WriteTo(wireHeader, buffer); var memory = new Memory <byte>(buffer, 0, WireHeader.Size); await _mainStream.WriteAsync(memory, cancellation).ConfigureAwait(false); _logger.LogDebug($"Written header {message.Header.ToString()}"); ArrayPool <byte> .Shared.Return(buffer); _logger.LogDebug($"Writing payload {message.Header.ToString()}"); await message.Payload.CopyIntoAsync(_mainStream, cancellation).ConfigureAwait(false); _logger.LogDebug($"Written payload {message.Header.ToString()}"); }
private async ValueTask Receive() { var buffer = new PooledMemoryStream(); Message message; try { await Receive(buffer, WireHeader.Size).ConfigureAwait(false); buffer.Position = 0; WireHeader wireHeader = WireHeader.ReadFrom(buffer); buffer.Reset(); await Receive(buffer, wireHeader.PayloadSize.Value).ConfigureAwait(false); buffer.Position = 0; message = new Message(wireHeader.MessageHeader, buffer); } catch (Exception ex) { if (!(ex is OperationCanceledException)) { //if (_logger.IsEnabled(LogLevel.Error)) //{ // _logger.LogError(ex, "Error during receive"); //} } //if(ex is SocketException sex && sex.ErrorCode == SocketError.TimedOut) buffer.Dispose(); return; } _session.EnqueueIncoming(message); }