Пример #1
0
        async Task ProcessTcpClient(TcpClient tcpClient, CancellationToken token)
        {
            try
            {
                // this worker thread stays alive until either of the following happens:
                // Client sends a close conection request OR
                // An unhandled exception is thrown OR
                // The server is disposed

                // get a secure or insecure stream
                Stream stream = tcpClient.GetStream();
                if (_secure)
                {
                    SslStream sslStream = new SslStream(stream, false, CertVerificationCallback);
                    sslStream.AuthenticateAsServer(_sslConfig.Certificate, _sslConfig.ClientCertificateRequired, _sslConfig.EnabledSslProtocols, _sslConfig.CheckCertificateRevocation);
                    stream = sslStream;
                }
                WebSocketHttpContext context = await webSocketServerFactory.ReadHttpHeaderFromStreamAsync(tcpClient, stream, token);

                if (context.IsWebSocketRequest)
                {
                    WebSocketServerOptions options = new WebSocketServerOptions()
                    {
                        KeepAliveInterval = TimeSpan.FromSeconds(30), SubProtocol = "binary"
                    };

                    WebSocket webSocket = await webSocketServerFactory.AcceptWebSocketAsync(context, options);

                    await ReceiveLoopAsync(webSocket, token);
                }
                else
                {
                    Debug.Log("Http header contains no web socket upgrade request. Ignoring");
                }
            }
            catch (IOException)
            {
                // do nothing. This will be thrown if the transport is closed
            }
            catch (ObjectDisposedException)
            {
                // do nothing. This will be thrown if the Listener has been stopped
            }
            catch (Exception ex)
            {
                ReceivedError?.Invoke(0, ex);
            }
            finally
            {
                try
                {
                    tcpClient.Client.Close();
                    tcpClient.Close();
                }
                catch (Exception ex)
                {
                    ReceivedError?.Invoke(0, ex);
                }
            }
        }
 public WebSocketConnection(WebSocketServer webSocketServer, WebSocket webSocket, string id, IServiceProvider serviceProvider)
 {
     _webSocketServer = webSocketServer;
     WebSocket        = webSocket;
     Id = id;
     _serviceProvider       = serviceProvider;
     _webSocketServerOption = serviceProvider.GetService <IOptions <WebSocketServerOptions> >().Value;
 }
Пример #3
0
 public GraphQLWSProtocol(
     IQueryStreamService queryStreamService,
     IOptions <WebSocketServerOptions> options,
     IMessageContextAccessor messageContextAccessor,
     ILogger <GraphQLWSProtocol> logger)
 {
     _queryStreamService     = queryStreamService;
     _messageContextAccessor = messageContextAccessor;
     _logger        = logger;
     _options       = options.Value;
     _parserOptions = new ParserOptions
     {
         ImportProviders = null
     };
 }
Пример #4
0
        public override async Task <IConnection> AcceptAsync()
        {
            try
            {
                TcpClient tcpClient = await listener.AcceptTcpClientAsync();

                var options = new WebSocketServerOptions {
                    KeepAliveInterval = TimeSpan.FromSeconds(30), SubProtocol = "binary"
                };

                Stream stream = tcpClient.GetStream();

                WebSocketHttpContext context = await webSocketServerFactory.ReadHttpHeaderFromStreamAsync(tcpClient, stream);

                WebSocket webSocket = await webSocketServerFactory.AcceptWebSocketAsync(context, options);

                return(new WebsocketConnection(webSocket));
            }
            catch (ObjectDisposedException)
            {
                // expected,  the connection was closed
                return(null);
            }
        }
Пример #5
0
        private async Task ProcessTcpClientAsync(TcpClient tcpClient)
        {
            CancellationTokenSource source = new CancellationTokenSource();

            try
            {
                if (_isDisposed)
                {
                    return;
                }

                // this worker thread stays alive until either of the following happens:
                // Client sends a close conection request OR
                // An unhandled exception is thrown OR
                // The server is disposed
                Console.WriteLine("Server: Connection opened. Reading Http header from stream");

                // get a secure or insecure stream
                Stream stream = tcpClient.GetStream();
                WebSocketHttpContext context = await _webSocketServerFactory.ReadHttpHeaderFromStreamAsync(stream);

                if (context.IsWebSocketRequest)
                {
                    // disable ping pong for now (it is causing multi-threaded issues)
                    var options = new WebSocketServerOptions()
                    {
                        KeepAliveInterval = TimeSpan.Zero
                    };
                    Console.WriteLine("Http header has requested an upgrade to Web Socket protocol. Negotiating Web Socket handshake");
                    WebSocket webSocket = await _webSocketServerFactory.AcceptWebSocketAsync(context, options);

                    Console.WriteLine("Web Socket handshake response sent. Stream ready.");
                    await RespondToWebSocketRequestAsync(webSocket, source.Token);
                }
                else
                {
                    Console.WriteLine("Http header contains no web socket upgrade request. Ignoring");
                }

                Console.WriteLine("Server: Connection closed");
            }
            catch (ObjectDisposedException)
            {
                // do nothing. This will be thrown if the Listener has been stopped
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                try
                {
                    tcpClient.Client.Close();
                    tcpClient.Close();
                    source.Cancel();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Failed to close TCP connection: {ex}");
                }
            }
        }
Пример #6
0
 /// <summary>
 /// 启用 WebSocketServer 服务端
 /// </summary>
 /// <param name="app"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static IApplicationBuilder UseWebSocketServer(this IApplicationBuilder app, WebSocketServerOptions options)
 {
     app.Map(options.PathMatch, appcur =>
     {
         var imserv = new WebSocketServer(options);
         if (options.IsWebSocket)
         {
             appcur.UseWebSockets();
         }
         appcur.Use((ctx, next) => imserv.Acceptor(ctx, next));
     });
     return(app);
 }
        /// <summary>
        /// 使用WebSocket服务端
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseWebSocketServer(this IApplicationBuilder app)
        {
            IServiceProvider         serviceProvider         = app.ApplicationServices;
            IHostApplicationLifetime hostApplicationLifetime = serviceProvider.GetService <IHostApplicationLifetime>();
            WebSocketServerOptions   option = serviceProvider.GetService <IOptions <WebSocketServerOptions> >().Value;
            ILogger         logger          = serviceProvider.GetService <ILoggerFactory>().CreateLogger(typeof(WebSocketServerExtentions));
            WebSocketServer webSocketServer = serviceProvider.GetService <WebSocketServer>();

            app.UseWebSockets();

            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

            hostApplicationLifetime.ApplicationStopping.Register(() => cancellationTokenSource.Cancel());
            app.Use(async(context, next) =>
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    using WebSocket webSocket      = await context.WebSockets.AcceptWebSocketAsync();
                    WebSocketConnection connection = new WebSocketConnection(
                        webSocketServer, webSocket, Guid.NewGuid().ToString(), serviceProvider);
                    webSocketServer.AddConnection(connection);
                    if (option.OnConnected != null)
                    {
                        await option.OnConnected(serviceProvider, connection);
                    }
                    logger.LogInformation("收到新的连接 当前连接数:{Count}", webSocketServer.ConnectionCount);

                    List <byte> bytes = new List <byte>();
                    try
                    {
                        while (true)
                        {
                            var buffer = new byte[1024];
                            WebSocketReceiveResult result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), cancellationTokenSource.Token);
                            if (result.CloseStatus.HasValue)
                            {
                                await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None);

                                break;
                            }

                            bytes.AddRange(new ArraySegment <byte>(buffer, 0, result.Count));
                            if (result.EndOfMessage)
                            {
                                //接收数据结束
                                var body = Encoding.UTF8.GetString(bytes.ToArray());

                                //使用内部总线转发,异步处理
                                await _busControl.Publish(new MessageReceivedEvent
                                {
                                    ConnectionId = connection.Id,
                                    Body         = body
                                });
                                bytes.Clear();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        if (ex is WebSocketException webSocketException && webSocketException.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely)
                        {
                            //忽略
                        }
                        else
                        {
                            logger.LogError(ex, ex.Message);
                        }
                    }
                    finally
                    {
                        webSocketServer.RemoveConnection(connection);
                        logger.LogInformation("连接关闭[{ConnectionId}] 当前连接数:{Count}", connection.Id, webSocketServer.ConnectionCount);
                    }
                }
Пример #8
0
        private async Task ProcessTcpClientAsync(TcpClient tcpClient)
        {
            CancellationTokenSource source = new CancellationTokenSource();

            if (_isDisposed)
            {
                return;
            }

            // this worker thread stays alive until either of the following happens:
            // Client sends a close conection request OR
            // An unhandled exception is thrown OR
            // The server is disposed

            // get a secure or insecure stream
            Stream stream = tcpClient.GetStream();

            if (Secure)
            {
                var sslStream = new SslStream(stream, false, CertVerificationCallback);
                await sslStream.AuthenticateAsServerAsync(_sslConfig.Certificate, _sslConfig.ClientCertificateRequired, _sslConfig.EnabledSslProtocols, _sslConfig.CheckCertificateRevocation);

                stream = sslStream;
            }
            WebSocketHttpContext context = await _webSocketServerFactory.ReadHttpHeaderFromStreamAsync(stream);

            if (context.IsWebSocketRequest)
            {
                if (context.Path == _GamePath)
                {
                    string subProtocol = GetSubProtocol(context.WebSocketRequestedProtocols);
                    var    options     = new WebSocketServerOptions()
                    {
                        KeepAliveInterval = TimeSpan.FromSeconds(30), SubProtocol = subProtocol
                    };

                    WebSocket webSocket = await _webSocketServerFactory.AcceptWebSocketAsync(context, options);

                    var newClient = Server.AddClient(new ClientContainer(System.Guid.NewGuid().ToString(), webSocket));
                    await newClient.ClientProcess();
                }
                else
                {
                    Console.WriteLine("path not match");
                }
            }
            else
            {
            }

            //}
            //catch (ObjectDisposedException)
            //{
            //    // do nothing. This will be thrown if the Listener has been stopped
            //}
            //finally
            //{
            //    try
            //    {
            //        tcpClient.Client.Close();
            //        tcpClient.Close();
            //        source.Cancel();
            //    }
            //    catch (Exception ex)
            //    {
            //    }
            //}
        }
Пример #9
0
        private async Task ProcessTcpClientAsync(TcpClient tcpClient)
        {
            var source = new CancellationTokenSource();

            this.activeClients.Add(tcpClient);

            try
            {
                if (this.isDisposed)
                {
                    return;
                }

                // this worker thread stays alive until either of the following happens:
                // Client sends a close connection request OR
                // An unhandled exception is thrown OR
                // The server is disposed
                Trace.TraceInformation("Server: Connection opened. Reading HTTP header from stream");

                // get a secure or insecure stream
                var stream = tcpClient.GetStream();
                WebSocketHttpContext context = await this.webSocketServerFactory.ReadHttpHeaderFromStreamAsync(stream);

                if (context.IsWebSocketRequest)
                {
                    var options = new WebSocketServerOptions()
                    {
                        KeepAliveInterval = TimeSpan.MaxValue
                    };
                    Trace.TraceInformation("HTTP header has requested an upgrade to Web Socket protocol. Negotiating Web Socket handshake");

                    var webSocket = await this.webSocketServerFactory.AcceptWebSocketAsync(context, options);

                    Trace.TraceInformation("Web Socket handshake response sent. Stream ready.");
                    await RespondToWebSocketRequestAsync(webSocket, source.Token);
                }
                else
                {
                    Trace.TraceInformation("HTTP header contains no web socket upgrade request. Ignoring");
                }

                Trace.TraceInformation("Server: Connection closed");
            }
            catch (ObjectDisposedException)
            {
                // Do nothing. This will be thrown if the Listener has been stopped
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
            }
            finally
            {
                this.activeClients.Remove(tcpClient);

                try
                {
                    tcpClient.Client.Close();
                    tcpClient.Close();
                    source.Cancel();
                }
                catch (Exception ex)
                {
                    Trace.TraceError($"Failed to close TCP connection: {ex}");
                }
            }
        }
Пример #10
0
        private async Task ProcessTcpClientAsync(TcpClient tcpClient)
        {
            CancellationTokenSource source = new CancellationTokenSource();

            try
            {
                if (_isDisposed)
                {
                    return;
                }
                // this worker thread stays alive until either of the following happens:
                // Client sends a close conection request OR
                // An unhandled exception is thrown OR
                // The server is disposed
                WSLog.Info("<Server>: Connection opened. Reading Http header from stream");
                WSLog.Info("-----------------------------------------------------------");

                // get a secure or insecure stream
                Stream stream = tcpClient.GetStream();
                WebSocketHttpContext context = await _webSocketServerFactory.ReadHttpHeaderFromStreamAsync(stream);

                if (context.IsWebSocketRequest)
                {
                    string subProtocol = GetSubProtocol(context.WebSocketRequestedProtocols);
                    var    options     = new WebSocketServerOptions()
                    {
                        KeepAliveInterval = TimeSpan.FromSeconds(30), SubProtocol = subProtocol
                    };
                    WSLog.Info("<Message>: Http header has requested an upgrade to Web Socket protocol. Negotiating Web Socket handshake");

                    WebSocket webSocket = await _webSocketServerFactory.AcceptWebSocketAsync(context, options);

                    WSLog.Info("<Message>: Web Socket handshake response sent. Stream ready.");
                    await RespondToWebSocketRequestAsync(webSocket, source.Token);
                }
                else
                {
                    WSLog.Info("<Message>: Http header contains no web socket upgrade request. Ignoring");
                }

                // closed connection
                WSLog.Info("-----------------------------------------------------------");
                WSLog.Info("<Server>: Connection closed.");
            }
            catch (ObjectDisposedException)
            {
                // do nothing. This will be thrown if the Listener has been stopped
            }
            catch (Exception ex)
            {
                WSLog.Error(ex.ToString());
            }
            finally
            {
                try
                {
                    tcpClient.Client.Close();
                    tcpClient.Close();
                    source.Cancel();
                }
                catch (Exception ex)
                {
                    WSLog.Error($"<Error>: failed to close TCP connection: {ex}");
                }
            }
        }
Пример #11
0
        /// <summary>
        /// 启用WebSocket功能,默认已经启用官方,无需多次启动
        /// </summary>
        public static IApplicationBuilder UseWebSocketsServer(this IApplicationBuilder app, WebSocketServerOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            app.UseWebSockets();

            return(app.UseMiddleware <WebSocketServerMiddleware>(Options.Create(options)));
        }