Пример #1
0
        private async Task <MemcachedResponse> ExecuteCommand(MemcachedRequest request)
        {
            await _protocolWriter.WriteAsync(_memcachedMessageWriter, request);

            var result = await _protocolReader.ReadAsync(_memcachedMessageReader);

            _protocolReader.Advance();
            return(result.Message);
        }
Пример #2
0
        public async Task SubscribeAsync(string topic, Func <string, ReadOnlyMemory <byte>, Task> callback)
        {
            if (_topics.TryGetValue(topic, out _))
            {
                return;
            }

            var id = Interlocked.Increment(ref _nextOperationId);

            var operation = new TaskCompletionSource <object>(TaskCreationOptions.RunContinuationsAsynchronously);

            _operations[id] = operation;

            _topics[topic] = callback;

            await _writer.WriteAsync(_protocol, new Message
            {
                Id          = id,
                MessageType = MessageType.Subscribe,
                Topic       = topic
            });

            await operation.Task;
        }
Пример #3
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();
                }
            }
        }
Пример #4
0
        public async Task ShortLengthMaskedWorksViaManagedWebSocket()
        {
            var options    = new PipeOptions(useSynchronizationContext: false);
            var duplexPipe = DuplexPipe.CreateConnectionPair(options, options);

            var webSocket = WebSocket.CreateFromStream(new DuplexPipeStream(duplexPipe.Application.Input, duplexPipe.Application.Output), true, null, TimeSpan.FromSeconds(30));
            var writer    = new WebSocketFrameWriter();

            var payloadString = String.Join(String.Empty, Enumerable.Repeat("This is a test payload.", 25));
            var payloadBuffer = new ReadOnlySequence <byte>(Encoding.UTF8.GetBytes(payloadString));
            var header        = WebSocketHeader.CreateMasked(true, WebSocketOpcode.Binary, (ulong)payloadBuffer.Length);

            var protocolWriter = new ProtocolWriter(duplexPipe.Transport.Output);
            await protocolWriter.WriteAsync(writer, new WebSocketWriteFrame(header, payloadBuffer));

            var receiveBuffer = new Memory <byte>(new byte[payloadBuffer.Length]);
            await webSocket.ReceiveAsync(receiveBuffer, default);

            Assert.Equal(payloadString, Encoding.UTF8.GetString(receiveBuffer.ToArray()));
        }
Пример #5
0
        /// <summary>
        ///     try send as an asynchronous operation.
        /// </summary>
        /// <param name="requestMessage">The request message.</param>
        /// <param name="cancellationToken">
        ///     The cancellation token that can be used by other objects or threads to receive notice
        ///     of cancellation.
        /// </param>
        /// <returns>A Task&lt;FlushResult&gt; representing the asynchronous operation.</returns>
        /// <exception cref="TheDesolatedTunnels.RelayServer.Core.Exceptions.ConnectionNotFoundException"></exception>
        /// <autogeneratedoc />
        public async ValueTask TrySendAsync(SixtyNineSendibleMessage requestMessage,
                                            CancellationToken cancellationToken = default)
        {
            await _semaphore.WaitAsync(cancellationToken).ConfigureAwait(false);

            try
            {
                var connection = _connectionStore[requestMessage.Destination] ??
                                 throw new ConnectionNotFoundException(requestMessage.Destination);
                // Write request message length
                //_messageWriter.WriteMessage(requestMessage, connection.Transport.Output);
                var ff = new ProtocolWriter(connection.Transport.Output);
                await ff.WriteAsync(_messageWriter, requestMessage, cancellationToken);
            }
            finally
            {
                _semaphore.Release();
            }

            //return await connection.Transport.Output.FlushAsync(cancellationToken);
        }
Пример #6
0
        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);
            }
        }
 public ValueTask SendAsync(IAmqpMessage message)
 {
     return(_writer.WriteAsync(_formatter, message));
 }
 internal ValueTask WriteAsync <T>(IMessageWriter <T> writer, T message, CancellationToken token = default)
 {
     return(Writer.WriteAsync(writer, message, token));
 }
Пример #9
0
 public ValueTask WriteAsync(INetworkMessage message, CancellationToken cancellationToken = default)
 {
     return(_writer.WriteAsync(_messageWriter, message, cancellationToken));
 }
 public ValueTask SendAsync(IRedisCommand message)
 {
     return(_writer.WriteAsync(_commandWriter, message));
 }