Ejemplo n.º 1
0
 private async Task ReceiveWebSocket(HttpListenerContext ctx, SharpWebSocket socket)
 {
     try
     {
         await socket.StartReceive().ConfigureAwait(false);
     }
     finally
     {
         TryClose(ctx, 200);
     }
 }
Ejemplo n.º 2
0
        private async Task ProcessWebSocketRequest(HttpListenerContext ctx)
        {
            try
            {
                var endpoint = ctx.Request.RemoteEndPoint.ToString();
                var url      = ctx.Request.RawUrl;

                var queryString = ctx.Request.QueryString;

                var connectingArgs = new WebSocketConnectingEventArgs
                {
                    Url         = url,
                    QueryString = queryString,
                    Endpoint    = endpoint
                };

                WebSocketConnecting?.Invoke(connectingArgs);

                if (connectingArgs.AllowConnection)
                {
                    _logger.LogDebug("Web socket connection allowed");

                    var webSocketContext = await ctx.AcceptWebSocketAsync(null).ConfigureAwait(false);

                    if (WebSocketConnected != null)
                    {
                        var socket = new SharpWebSocket(webSocketContext.WebSocket, _logger);
                        await socket.ConnectAsServerAsync().ConfigureAwait(false);

                        WebSocketConnected(new WebSocketConnectEventArgs
                        {
                            Url         = url,
                            QueryString = queryString,
                            WebSocket   = socket,
                            Endpoint    = endpoint
                        });

                        await socket.StartReceive().ConfigureAwait(false);
                    }
                }
                else
                {
                    _logger.LogWarning("Web socket connection not allowed");
                    TryClose(ctx, 401);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "AcceptWebSocketAsync error");
                TryClose(ctx, 500);
            }
        }