示例#1
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            // Use a length prefixed protocol
            var protocol = new LengthPrefixedProtocol();
            var reader   = connection.CreateReader();
            var writer   = connection.CreateWriter();

            while (true)
            {
                try
                {
                    var result = await reader.ReadAsync(protocol);

                    var message = result.Message;

                    _logger.LogInformation("Received a message of {Length} bytes", message.Payload.Length);

                    if (result.IsCompleted)
                    {
                        break;
                    }

                    await writer.WriteAsync(protocol, message);
                }
                finally
                {
                    reader.Advance();
                }
            }
        }
示例#2
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            IServiceScope      scope         = null;
            BlazeClientContext clientContext = null;

            try
            {
                //Create connection scope
                scope = _serviceScopeFactory.CreateScope();
                var messageHandler = scope.ServiceProvider.GetRequiredService <IBlazeMessageHandler>();

                clientContext = (BlazeClientContext)scope.ServiceProvider.GetRequiredService <ClientContext>();
                clientContext.ConnectionContext = connection;
                _clientManager.Add(clientContext);

                var reader = connection.CreateReader();
                var writer = connection.CreateWriter();

                while (true)
                {
                    try
                    {
                        var result = await reader.ReadAsync(_protocol);

                        var message = result.Message;

                        if (message != null)
                        {
                            var responses = await messageHandler.ProcessMessage(message, clientContext);

                            if (responses != null)
                            {
                                foreach (var response in responses)
                                {
                                    await writer.WriteAsync(_protocol, response);
                                }
                            }
                        }

                        if (result.IsCompleted)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        reader.Advance();
                    }
                }
            }
            finally
            {
                if (clientContext != null)
                {
                    _clientManager.Remove(clientContext);
                }

                scope?.Dispose();
            }
        }
示例#3
0
        public CobbleConnection(ConnectionContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _reader  = context.CreateReader();
            _writer  = context.CreateWriter();

            _protocol = new HandshakingProtocol();
        }
示例#4
0
 private HubProtocol(ConnectionContext connection, int?maximumMessageSize, IHubProtocol hubProtocol, IInvocationBinder invocationBinder)
 {
     _connection         = connection;
     _protocolReader     = connection.CreateReader();
     _protocolWriter     = connection.CreateWriter();
     _hubMessageReader   = new HubMessageReader(hubProtocol, invocationBinder);
     _hubMessageWriter   = new HubMessageWriter(hubProtocol);
     _maximumMessageSize = maximumMessageSize;
 }
示例#5
0
        public async Task ConnectAsync(EndPoint endPoint)
        {
            // REVIEW: Should this be a static factory?
            _connection = await _client.ConnectAsync(endPoint).ConfigureAwait(false);

            _writer      = _connection.CreateWriter();
            _reader      = _connection.CreateReader();
            _readingTask = ProcessReadsAsync();
        }
示例#6
0
        public MemcachedProtocol(ConnectionContext connection)
        {
            _connection = connection;

            _protocolReader = connection.CreateReader();
            _protocolWriter = connection.CreateWriter();

            _semaphore = new SemaphoreSlim(1);

            _memcachedMessageWriter = new MemcachedMessageWriter();
            _memcachedMessageReader = new MemcachedMessageReader();
        }
示例#7
0
        /// <summary>
        /// on connected as an asynchronous operation.
        /// </summary>
        /// <param name="connection">The new <see cref="T:Microsoft.AspNetCore.Connections.ConnectionContext" /></param>
        /// <returns>A <see cref="T:System.Threading.Tasks.Task" /> that represents the connection lifetime. When the task completes, the connection is complete.</returns>
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            this.context = connection;
            this.reader  = connection.CreateReader();
            this.writer  = connection.CreateWriter();

            SessionManager.Singleton.AcceptSession(connection, writer, this.protocol);

            //IConnectionHeartbeatFeature heartbeatFeature = connection.Features.Get<IConnectionHeartbeatFeature>();
            //heartbeatFeature.OnHeartbeat(this.SendHeartbeat, null);

            while (true)
            {
                try
                {
                    var result = await reader.ReadAsync(protocol);

                    var message = result.Message;

                    _logger.LogInformation("Received a message of {Length} bytes", message.Payload.Length);

                    if (result.IsCompleted)
                    {
                        break;
                    }



                    await writer.WriteAsync(protocol, message);
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message);
                    connection.Abort();
                    break;
                }
                finally
                {
                    reader.Advance();
                }
            }
        }
 public RabbitMQClientProtocol(ConnectionContext connection)
 {
     _writer    = connection.CreateWriter();
     _reader    = connection.CreateReader();
     _formatter = new RabbitMQMessageFormatter();
 }
示例#9
0
 public RespBedrockProtocol(ConnectionContext connection)
 {
     // _connection = connection;
     _reader = connection.CreateReader();
     _writer = connection.CreateWriter();
 }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            // TODO: we could register processors as Scoped per connection and create a scope here
            //using var serviceProviderScope = serviceProvider.CreateScope();

            if (connection is null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            using IDisposable logScope = _logger.BeginScope("Peer {PeerId} connected to outbound {PeerEndpoint}", connection.ConnectionId, connection.LocalEndPoint);

            ProtocolReader reader = connection.CreateReader();
            INetworkProtocolMessageSerializer protocol = _serviceProvider.GetRequiredService <INetworkProtocolMessageSerializer>();

            using IPeerContext peerContext = _peerContextFactory.CreateOutgoingPeerContext(connection.ConnectionId,
                                                                                           connection.LocalEndPoint !,
                                                                                           connection.Features.Get <OutgoingConnectionEndPoint>(),
                                                                                           new NetworkMessageWriter(protocol, connection.CreateWriter()));

            connection.ConnectionClosed = peerContext.ConnectionCancellationTokenSource.Token;
            connection.Features.Set(peerContext);

            protocol.SetPeerContext(peerContext);

            _eventBus.Publish(new PeerConnected(peerContext));


            await _networkMessageProcessorFactory.StartProcessorsAsync(peerContext).ConfigureAwait(false);


            while (true)
            {
                if (connection.ConnectionClosed.IsCancellationRequested)
                {
                    break;
                }

                try
                {
                    ProtocolReadResult <INetworkMessage> result =
                        await reader.ReadAsync(protocol, connection.ConnectionClosed).ConfigureAwait(false);

                    if (result.IsCompleted)
                    {
                        break;
                    }

                    await ProcessMessageAsync(result.Message, peerContext, connection.ConnectionClosed)
                    .WithCancellationAsync(connection.ConnectionClosed)
                    .ConfigureAwait(false);
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                catch (Exception e)
                {
                    _logger.LogError(new EventId(0), e, e.Message);
                    throw;
                }
                finally
                {
                    reader.Advance();
                }
            }

            return;
        }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            IServiceScope      scope         = null;
            BlazeClientContext clientContext = null;

            try
            {
                //Create connection scope
                scope = _serviceScopeFactory.CreateScope();
                var messageHandler = scope.ServiceProvider.GetRequiredService <IBlazeMessageHandler>();

                clientContext = (BlazeClientContext)scope.ServiceProvider.GetRequiredService <ClientContext>();
                clientContext.ConnectionContext = connection;
                clientContext.Reader            = connection.CreateReader();
                clientContext.Writer            = connection.CreateWriter();

                _clientManager.Add(clientContext);

                while (true)
                {
                    try
                    {
                        var result = await clientContext.Reader.ReadAsync(_protocol);

                        var message = result.Message;

                        if (message != null)
                        {
                            var response = await messageHandler.ProcessMessage(message);

                            if (response != null)
                            {
                                await clientContext.Writer.WriteAsync(_protocol, response);
                            }
                            //Send new notifications
                            while (clientContext.PendingNotifications.TryDequeue(out var notification))
                            {
                                await clientContext.Writer.WriteAsync(_protocol, notification);
                            }
                        }

                        if (result.IsCompleted)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        clientContext.Reader.Advance();
                    }
                }
            }
            finally
            {
                if (clientContext != null)
                {
                    _clientManager.Remove(clientContext);
                }

                scope?.Dispose();
            }
        }
 public RabbitMQProtocolWriter(ConnectionContext ctx)
 {
     Writer = ctx.CreateWriter();
 }
示例#13
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            if (connection is null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            using IDisposable loggerScope = _logger.BeginScope("Peer {PeerId} connected to server {ServerEndpoint}", connection.ConnectionId, connection.LocalEndPoint);

            ProtocolReader reader = connection.CreateReader();
            INetworkProtocolMessageSerializer protocol = _serviceProvider.GetRequiredService <INetworkProtocolMessageSerializer>();

            using IPeerContext peerContext = _peerContextFactory.CreateIncomingPeerContext(connection.ConnectionId,
                                                                                           connection.LocalEndPoint !.AsIPEndPoint().EnsureIPv6(),
                                                                                           connection.RemoteEndPoint !.AsIPEndPoint().EnsureIPv6(),
                                                                                           new NetworkMessageWriter(protocol, connection.CreateWriter()));

            using CancellationTokenRegistration cancellationRegistration = peerContext.ConnectionCancellationTokenSource.Token.Register(() =>
            {
                connection.Abort(new ConnectionAbortedException("Requested by PeerContext"));
            });

            connection.Features.Set(peerContext);
            protocol.SetPeerContext(peerContext);

            if (EnsurePeerCanConnect(connection, peerContext))
            {
                _eventBus.Publish(new PeerConnected(peerContext));

                await _networkMessageProcessorFactory.StartProcessorsAsync(peerContext).ConfigureAwait(false);

                while (true)
                {
                    try
                    {
                        ProtocolReadResult <INetworkMessage> result = await reader.ReadAsync(protocol).ConfigureAwait(false);

                        if (result.IsCompleted)
                        {
                            break;
                        }

                        await ProcessMessageAsync(result.Message, peerContext, connection.ConnectionClosed).ConfigureAwait(false);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogDebug(ex, "Unexpected connection terminated because of {DisconnectionReason}.", ex.Message);
                        break;
                    }
                    finally
                    {
                        reader.Advance();
                    }
                }

                return;
            }
        }
 public RedisProtocol(ConnectionContext connection)
 {
     _writer        = connection.CreateWriter();
     _reader        = connection.CreateReader();
     _commandWriter = new RedisCommandWriter();
 }
示例#15
0
 public RespBedrockProtocol(ConnectionContext connection, object state = null) : base(state)
 {
     // _connection = connection;
     _reader = connection.CreateReader();
     _writer = connection.CreateWriter();
 }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            Logger.Debug($"Redirecting to {_proxySettings.RedirectHost} {_proxySettings.RedirectIp}:{_proxySettings.LocalPort}");

            var blazeProtocol = new BlazeProxyProtocol();
            var localReader   = connection.CreateReader();
            var localWriter   = connection.CreateWriter();

            while (true)
            {
                try
                {
                    var result = await localReader.ReadAsync(blazeProtocol);

                    var message = result.Message;

                    if (message != null)
                    {
                        if (message.Header.Component == BlazeComponent.Redirector &&
                            message.Header.Command == (ushort)RedirectorCommand.ServerInfo)
                        {
                            var hostBytes = new List <byte>(Encoding.ASCII.GetBytes(_proxySettings.RedirectHost));
                            var payload   = new List <byte>();
                            payload.AddRange(new byte[] {
                                0x86, 0x49, 0x32, //ADDR
                                0xD0, 0x00,       //union(0)
                                0xDA, 0x1B, 0x35, //VALU
                                0x00,             //start struct
                                0xA2, 0xFC, 0xF4, //HOST
                            });
                            payload.AddRange(GetStringLengthBytes((uint)hostBytes.Count + 1));
                            payload.AddRange(hostBytes);
                            payload.AddRange(new byte[] {
                                0x00,             //endbyte for string
                                0xA7, 0x00, 0x00, //IP
                                0x74,             //uint32
                            });
                            var ipBytes = BitConverter.GetBytes(Convert.ToUInt32(IPAddress.Parse(_proxySettings.RedirectIp).Address));
                            Array.Reverse(ipBytes); //big endian
                            payload.AddRange(ipBytes);
                            payload.AddRange(new byte[] {
                                0xC2, 0xFC, 0xB4, //PORT
                                0x52,             //uint16
                            });
                            var portBytes = BitConverter.GetBytes(Convert.ToUInt16(_proxySettings.LocalPort));
                            Array.Reverse(portBytes); //big endian
                            payload.AddRange(portBytes);
                            payload.AddRange(new byte[] {
                                0x00,                   //end struct
                                0xCE, 0x58, 0xF5,       //SECU
                                0x21,                   //int8
                                0x00,                   //0
                                0xE2, 0x4B, 0xB3,       //XDNS
                                0x74,                   //uint32
                                0x00, 0x00, 0x00, 0x00, //0
                            });
                            var response = new BlazeMessageData
                            {
                                Header = new BlazeHeader
                                {
                                    Command     = message.Header.Command,
                                    Component   = message.Header.Component,
                                    MessageType = BlazeMessageType.Reply,
                                    MessageId   = message.Header.MessageId,
                                    ErrorCode   = 0
                                },
                                Payload = new ReadOnlySequence <byte>(payload.ToArray())
                            };
                            await localWriter.WriteAsync(blazeProtocol, response);
                        }
                    }

                    if (result.IsCompleted)
                    {
                        break;
                    }
                }
                finally
                {
                    localReader.Advance();
                }
            }
        }
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            Logger.Debug($"Connecting to {_proxySettings.RemoteHost}:{_proxySettings.RemotePort}");
            var proxyClient = new TcpClient();
            await proxyClient.ConnectAsync(_proxySettings.RemoteHost, _proxySettings.RemotePort);

            var ogStream = proxyClient.GetStream();

            Stream proxyStream = ogStream;

            if (_proxySettings.Secure)
            {
                var protocol = new TlsClientProtocol(proxyStream, new Org.BouncyCastle.Security.SecureRandom());
                protocol.Connect(new BlazeTlsClient());
                proxyStream = protocol.Stream;
            }

            var blazeProtocol = new BlazeProxyProtocol();
            var localReader   = connection.CreateReader();
            var localWriter   = connection.CreateWriter();

            var remoteReader = new ProtocolReader(proxyStream);
            var remoteWriter = new ProtocolWriter(proxyStream);


            while (true)
            {
                try
                {
                    var result = await localReader.ReadAsync(blazeProtocol);

                    var message = result.Message;

                    if (message != null)
                    {
                        var header = message.Header;
                        Logger.Debug(
                            $"Client -> Proxy; Length:{header.Length} Component:{header.Component} Command:0x{header.Command:X2} ErrorCode:{header.ErrorCode} MessageType:{header.MessageType} MessageId:{header.MessageId}");

                        var requestPayload = message.Payload;

                        if (!requestPayload.IsEmpty)
                        {
                            if (!_parser.TryParseBody(requestPayload))
                            {
                                Logger.Error("Failed to parse request message");
                            }
                        }

                        await remoteWriter.WriteAsync(blazeProtocol, message);
                    }

                    if (result.IsCompleted)
                    {
                        break;
                    }
                }
                finally
                {
                    localReader.Advance();
                }

                do
                {
                    try
                    {
                        var result = await remoteReader.ReadAsync(blazeProtocol);

                        var message = result.Message;

                        if (message != null)
                        {
                            var header = message.Header;
                            Logger.Debug(
                                $"Proxy <- Server; Length:{header.Length} Component:{header.Component} Command:0x{header.Command:X2} ErrorCode:{header.ErrorCode} MessageType:{header.MessageType} MessageId:{header.MessageId}");

                            var responsePayload = message.Payload;

                            if (!responsePayload.IsEmpty)
                            {
                                if (!_parser.TryParseBody(responsePayload))
                                {
                                    Logger.Error("Failed to parse response message");
                                }
                            }

                            await localWriter.WriteAsync(blazeProtocol, message);
                        }

                        if (result.IsCompleted)
                        {
                            break;
                        }
                    }
                    finally
                    {
                        remoteReader.Advance();
                    }
                } while (ogStream.DataAvailable);
            }
        }
示例#18
0
        public override async Task OnConnectedAsync(ConnectionContext connection)
        {
            var protocol         = new MessageReaderWriter();
            var reader           = connection.CreateReader();
            var writer           = connection.CreateWriter();
            var connectionTopics = new List <string>();

            try
            {
                while (true)
                {
                    var result = await reader.ReadAsync(protocol);

                    var message = result.Message;

                    if (result.IsCompleted)
                    {
                        break;
                    }

                    switch (message.MessageType)
                    {
                    case MessageType.Publish:
                    {
                        if (_topics.TryGetValue(message.Topic, out var topic))
                        {
                            var data = new Message
                            {
                                MessageType = MessageType.Data,
                                Payload     = message.Payload,
                                Topic       = message.Topic
                            };

                            topic.IncrementPublish();

                            // TODO: Use WhenAll
                            foreach (var pair in topic)
                            {
                                await pair.Value.WriteAsync(protocol, data);
                            }
                        }

                        await writer.WriteAsync(protocol, new Message
                            {
                                Id          = message.Id,
                                Topic       = message.Topic,
                                MessageType = MessageType.Success
                            });
                    }
                    break;

                    case MessageType.Subscribe:
                    {
                        var topic = _topics.GetOrAdd(message.Topic);

                        topic.Add(connection.ConnectionId, writer);

                        connectionTopics.Add(message.Topic);

                        await writer.WriteAsync(protocol, new Message
                            {
                                Id          = message.Id,
                                Topic       = message.Topic,
                                MessageType = MessageType.Success
                            });
                    }
                    break;

                    case MessageType.Unsubscribe:
                    {
                        RemoveTopic(connection, connectionTopics, message.Topic);

                        await writer.WriteAsync(protocol, new Message
                            {
                                Id          = message.Id,
                                Topic       = message.Topic,
                                MessageType = MessageType.Success
                            });
                    }
                    break;

                    default:
                        break;
                    }

                    reader.Advance();
                }
            }
            finally
            {
                for (int i = connectionTopics.Count - 1; i >= 0; i--)
                {
                    RemoveTopic(connection, connectionTopics, connectionTopics[i]);
                }
            }
        }