Ejemplo n.º 1
0
        public ClientWebSocketHandler(WebSocketTransport webSocketTransport)
            : base(maxIncomingMessageSize: null)
        {
            Debug.Assert(webSocketTransport != null, "webSocketTransport is null");

            _webSocketTransport = webSocketTransport;
        }
Ejemplo n.º 2
0
        public void AbortUrlTriggersContentTypeSet()
        {
            var request = new Mock <IRequest>();
            var qs      = new NameValueCollection();

            request.Setup(m => m.QueryString).Returns(new NameValueCollectionWrapper(qs));
            request.Setup(m => m.LocalPath).Returns("/test/echo/abort");
            var response            = new Mock <IResponse>();
            var counters            = new Mock <IPerformanceCounterManager>();
            var heartBeat           = new Mock <ITransportHeartbeat>();
            var hostContext         = new HostContext(request.Object, response.Object);
            var transportConnection = new Mock <ITransportConnection>();
            var traceManager        = new Mock <ITraceManager>();
            var transport           = new WebSocketTransport(hostContext, null, heartBeat.Object, counters.Object, traceManager.Object, null, null);

            transport.ProcessRequest(transportConnection.Object).Wait();
            response.VerifySet(r => r.ContentType = It.IsAny <string>(), "ContentType not set");
        }
        public async Task ShouldSupportCustomTransport()
        {
            var customTransportCreated = false;
            var options = new ConnectOptions()
            {
                BrowserWSEndpoint = Browser.WebSocketEndpoint,
                TransportFactory  = (url, opt, cancellationToken) =>
                {
                    customTransportCreated = true;
                    return(WebSocketTransport.DefaultTransportFactory(url, opt, cancellationToken));
                }
            };

            await using (await Puppeteer.ConnectAsync(options, TestConstants.LoggerFactory))
            {
                Assert.True(customTransportCreated);
            }
        }
Ejemplo n.º 4
0
        public async Task ConnectAsync(WebSocket webSocket, string connectionId, string connectorName = "")
        {
            var receiverContext = new WebSocketReceiverContext
            {
                Compressor    = _compressor,
                ConnectionId  = connectionId,
                LoggerFactory = _loggerFactory,
                WebSocket     = webSocket
            };

            WebSocketTransport transport = null;

            if (Connections.TryGetValue(connectionId, out transport))
            {
                transport.ReConnect(webSocket);
                List <MessageHolder> messages = _lifetimeManager.TryDequeue(connectionId);
                foreach (var message in messages)
                {
                    await SendAsync(transport, new WebSocketMessageDescriptor
                    {
                        MessageType  = WebSocketMessageType.Text,
                        Segments     = message.Segments,
                        EndOfMessage = true,
                        IsQueue      = true,
                    });
                }
            }
            else
            {
                transport = new WebSocketTransport(webSocket, connectionId, connectorName);
                var context = new WebSocketMessageContext();
                context.Command = WebSocketCommands.Handshake;
                context.Value   = connectionId;
                context.Header  = await _initState.GetStateAsync();

                Connections.TryAdd(connectionId, transport);

                await SendAsync(connectionId, context);
            }

            var receiver = new WebSocketReceiver(_serviceProvider, receiverContext, CloseConnection);
            await receiver.ReceiveAsync();
        }
Ejemplo n.º 5
0
        public void CloseConnection(string connectionId, bool keepAlive)
        {
            WebSocketTransport transport = null;

            if (keepAlive)
            {
                if (Connections.TryGetValue(connectionId, out transport))
                {
                    transport.Dispose();
                }
            }
            else
            {
                if (Connections.TryRemove(connectionId, out transport))
                {
                    transport.Dispose();
                }
            }
        }
Ejemplo n.º 6
0
        private Task SendBinaryAsync(WebSocketTransport transport, byte[] chunkedBytes, bool endOfMessage)
        {
            if (transport == null)
            {
                throw new ArgumentNullException(nameof(transport));
            }

            var segments = new ArraySegment <byte>(chunkedBytes);

            if (!transport.WebSocket.CloseStatus.HasValue)
            {
                return(transport.WebSocket.SendAsync(segments,
                                                     WebSocketMessageType.Binary,
                                                     endOfMessage,
                                                     CancellationToken.None));
            }

            return(TaskCache.CompletedTask);
        }
Ejemplo n.º 7
0
        public async Task ConnectAsync(WebSocket webSocket,
                                       string connectionId,
                                       string connectorName = "",
                                       CancellationToken cancellationToken = default(CancellationToken))
        {
            if (cancellationToken != CancellationToken.None)
            {
                cancellationToken.Register(() =>
                {
                    CancellationGraceful();
                });
            }

            var receiverContext = new WebSocketReceiverContext
            {
                Compressor       = _compressor,
                ConnectionId     = connectionId,
                LoggerFactory    = _loggerFactory,
                WebSocket        = webSocket,
                InvocatorContext = InvocatorContext
            };

            if (Connections.TryGetValue(connectionId, out WebSocketTransport transport))
            {
                transport.ReConnect(webSocket);
            }
            else
            {
                transport = new WebSocketTransport(webSocket, connectionId, connectorName);
                var context = new WebSocketMessageContext();
                context.Command = WebSocketCommands.Handshake;
                context.Value   = connectionId;
                context.Header  = await _initState.GetStateAsync();

                Connections.TryAdd(connectionId, transport);

                await SendAsync(connectionId, context);
            }

            var receiver = new WebSocketReceiver(_serviceProvider, receiverContext, CloseConnection, _loggerFactory);
            await receiver.ReceiveAsync(cancellationToken);
        }
Ejemplo n.º 8
0
        public void WebSocketSendReturnsAFaultedTaskWhenNotConnected(WebSocketState state)
        {
            var mockConnection = new Mock <Client.IConnection>(MockBehavior.Strict);
            var mockWebSocket  = new Mock <WebSocket>(MockBehavior.Strict);

            mockWebSocket.SetupGet(ws => ws.State).Returns(state);
            mockConnection.Setup(c => c.OnError(It.IsAny <InvalidOperationException>()));

            var wsTransport = new WebSocketTransport();

            wsTransport.WebSocket = mockWebSocket.Object;

            var task = wsTransport.Send(mockConnection.Object, "", "");

            Assert.True(task.IsFaulted);
            Assert.IsType(typeof(InvalidOperationException), task.Exception.InnerException);

            mockConnection.VerifyAll();
            mockWebSocket.VerifyAll();
        }
Ejemplo n.º 9
0
            async Task HandleListenerContextAsync(HttpListenerContext context)
            {
                WebSocket webSocket = null;

                try
                {
                    var wsContext = await context.AcceptWebSocketAsync(WebSocketTransport.WebSocketSubProtocol);

                    var wsTransport = new WebSocketTransport(wsContext.WebSocket);
                    await this.listener.HandleTransportAsync(wsTransport);
                }
                catch (Exception exception)
                {
                    Trace.WriteLine(TraceLevel.Error, exception.ToString());
                    if (webSocket != null)
                    {
                        webSocket.Abort();
                    }
                }
            }
Ejemplo n.º 10
0
        public SimpleServer()
        {
            ITransport websocketTransport = new WebSocketTransport();

            TransportRegistry.Instance.RegisterTransport(websocketTransport);

            IProtocol jsonRpc   = new JsonRpcProtocol();
            IProtocol fivesJson = new FiVESJsonProtocol();

            ProtocolRegistry.Instance.RegisterProtocol(jsonRpc);
            ProtocolRegistry.Instance.RegisterProtocol(fivesJson);

            SINFONIServer newServer = new SINFONIServer("localhost", 8080, "/service/", "server.sinfoni");
            var           service   = newServer.StartService("127.0.0.1", 34568, "/service", "ws", "jsonrpc");

            service.OnNewClient          += new NewClient(HandleNewClient);
            service["example.addVectors"] = (Func <Vector, Vector, Vector>)addVectors;

            Console.Read();
        }
        public async Task WebSocketTransport_WhatIsReceivedIsWritten()
        {
            var pipePair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);

            using (var webSocketFeature = new TestWebSocketConnectionFeature())
            {
                // Build transport
                var transport = new WebSocketTransport(await webSocketFeature.AcceptAsync(), pipePair.Application, NullLogger.Instance);

                // Accept web socket, start receiving / sending at the transport level
                var processTask = transport.ConnectAsync(CancellationToken.None);

                // Start a socket client that will capture traffic for posterior analysis
                var clientTask = webSocketFeature.Client.ExecuteAndCaptureFramesAsync();

                // Send a frame, then close
                await webSocketFeature.Client.SendAsync(
                    buffer : new ArraySegment <byte>(Encoding.UTF8.GetBytes("Hello")),
                    messageType : WebSocketMessageType.Binary,
                    endOfMessage : true,
                    cancellationToken : CancellationToken.None);

                await webSocketFeature.Client.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None);

                var result = await pipePair.Transport.Input.ReadAsync();

                var buffer = result.Buffer;
                Assert.Equal("Hello", Encoding.UTF8.GetString(buffer.ToArray()));
                pipePair.Transport.Input.AdvanceTo(buffer.End);

                pipePair.Transport.Output.Complete();

                // The transport should finish now
                await processTask;

                // The connection should close after this, which means the client will get a close frame.
                var clientSummary = await clientTask;

                Assert.Equal(WebSocketCloseStatus.NormalClosure, clientSummary.CloseResult.CloseStatus);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Creates and starts opening/upgrading process of the transports.
        /// </summary>
        private void CreateTransports()
        {
            bool hasWSSupport = Handshake.Upgrades.Contains("websocket");

            if (hasWSSupport)
            {
                Transport = new WebSocketTransport(this);
            }

            Poller = new PollingTransport(this);
            Poller.Open();

            if (Transport == null)
            {
                Transport = Poller as ITransport;
            }
            else
            {
                Transport.Open();
            }
        }
        /// <summary>
        /// This function will begin to open the Socket.IO connection by sending out the handshake request.
        /// If the Options' AutoConnect is true, it will be called automatically.
        /// </summary>
        public void Open()
        {
            if (State != States.Initial &&
                State != States.Closed &&
                State != States.Reconnecting)
            {
                return;
            }

            HTTPManager.Logger.Information("SocketManager", "Opening");

            ReconnectAt = DateTime.MinValue;

            switch (Options.ConnectWith)
            {
            case TransportTypes.Polling:
                Transport = new PollingTransport(this);
                break;

#if !BESTHTTP_DISABLE_WEBSOCKET
            case TransportTypes.WebSocket:
                Transport = new WebSocketTransport(this);
                break;
#endif
            }
            Transport.Open();


            (this as IManager).EmitEvent("connecting");

            State = States.Opening;

            ConnectionStarted = DateTime.UtcNow;

            HTTPManager.Heartbeats.Subscribe(this);

            // The root namespace will be opened by default
            GetSocket("/");
        }
Ejemplo n.º 14
0
        public static async Task <IConnectionTransport> CreateTransportAsync(ConnectOptions options)
        {
            if (!string.IsNullOrEmpty(options.BrowserWSEndpoint) && options.TransportFactory != null)
            {
                throw new ArgumentException("Exactly one of BrowserWSEndpoint or TransportFactory must be passed to connect");
            }

            IConnectionTransport transport = null;

            if (options.TransportFactory != null)
            {
                transport = await options.TransportFactory(new Uri(options.BrowserWSEndpoint), options).ConfigureAwait(false);
            }
            else if (!string.IsNullOrEmpty(options.BrowserWSEndpoint))
            {
#pragma warning disable CA2000 // Call dispose, this is a false alarm.
                transport = await WebSocketTransport.CreateAsync(options).ConfigureAwait(false);

#pragma warning restore CA2000
            }

            return(SlowMoTransport.Wrap(transport, options.SlowMo));
        }
Ejemplo n.º 15
0
        public Task SendAsync(string connectionId, WebSocketMessageContext context)
        {
            if (!Connections.Any())
            {
                return(TaskCache.CompletedTask);
            }

            WebSocketTransport transport = null;

            if (!Connections.TryGetValue(connectionId, out transport))
            {
                throw new ArgumentOutOfRangeException(nameof(transport));
            }

            var segments   = context.ToSegment();
            var descriptor = new WebSocketMessageDescriptor
            {
                Segments     = segments,
                EndOfMessage = true,
                MessageType  = WebSocketMessageType.Text
            };

            return(SendAsync(transport, descriptor));
        }
Ejemplo n.º 16
0
        internal async Task ConnectInternalAsync(Func <WebSocketTransport, Task> connectFunc, CancellationToken cancellationToken)
        {
            CheckDisposed();

            TimerAwaitable timer     = null;
            Task           timerTask = null;

            try
            {
                // Pipes
                _duplexPipePair = DuplexPipe.CreateConnectionPair(PipeOptions.Default, PipeOptions.Default);

                // Transport
                var transport = new WebSocketTransport(_duplexPipePair.Application, _logger);

                // Application
                _transportHandler = new TransportHandler(_duplexPipePair.Transport, _logger);

                // Session
                _session = new StreamingSession(_requestHandler, _transportHandler, _logger, cancellationToken);

                // Set up cancellation
                _disconnectCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

                // Start transport and application
                var transportTask   = connectFunc(transport);
                var applicationTask = _transportHandler.ListenAsync(_disconnectCts.Token);
                var combinedTask    = Task.WhenAll(transportTask, applicationTask);

                Log.ClientStarted(_logger, _url ?? string.Empty);

                // Periodic task: keep alive
                // Disposed with `timer.Stop()` in the finally block below
                if (_keepAlive.HasValue)
                {
                    timer     = new TimerAwaitable(_keepAlive.Value, _keepAlive.Value);
                    timerTask = TimerLoopAsync(timer);
                }

                // We are connected!
                IsConnected = true;

                // Block until transport or application ends.
                await combinedTask.ConfigureAwait(false);

                // Signal that we're done
                _disconnectCts.Cancel();
                Log.ClientTransportApplicationCompleted(_logger, _url);
            }
            finally
            {
                timer?.Stop();

                if (timerTask != null)
                {
                    await timerTask.ConfigureAwait(false);
                }
            }

            Log.ClientCompleted(_logger, _url ?? string.Empty);
        }
 private void RegisterModules()
 {
     var JsonRPCProtocol = new JsonRpcProtocol();
     var FiVESJsonProtocol = new FiVESJsonProtocol();
     var WebsocketTransport = new WebSocketTransport();
     KIARA.ProtocolRegistry.Instance.RegisterProtocol(JsonRPCProtocol);
     KIARA.ProtocolRegistry.Instance.RegisterProtocol(FiVESJsonProtocol);
     KIARA.TransportRegistry.Instance.RegisterTransport(WebsocketTransport);
 }
Ejemplo n.º 18
0
 async Task HandleListenerContextAsync(HttpListenerContext context)
 {
     WebSocket webSocket = null;
     try
     {
         var wsContext = await context.AcceptWebSocketAsync(WebSocketTransport.WebSocketSubProtocol);
         var wsTransport = new WebSocketTransport(wsContext.WebSocket);
         await this.listener.HandleTransportAsync(wsTransport);
     }
     catch(Exception exception)
     {
         Trace.WriteLine(TraceLevel.Error, exception.ToString());
         if (webSocket != null)
         {
             webSocket.Abort();
         }
     }
 }