Exemplo n.º 1
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
                };

                if (WebSocketConnecting != null)
                {
                    WebSocketConnecting(connectingArgs);
                }

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

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

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

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

                        await ReceiveWebSocket(ctx, socket).ConfigureAwait(false);
                    }
                }
                else
                {
                    _logger.Warn("Web socket connection not allowed");
                    ctx.Response.StatusCode = 401;
                    ctx.Response.Close();
                }
            }
            catch (Exception ex)
            {
                _logger.ErrorException("AcceptWebSocketAsync error", ex);
                ctx.Response.StatusCode = 500;
                ctx.Response.Close();
            }
        }
Exemplo n.º 2
0
 private async Task ReceiveWebSocket(HttpListenerContext ctx, SharpWebSocket socket)
 {
     try
     {
         await socket.StartReceive().ConfigureAwait(false);
     }
     finally
     {
         TryClose(ctx, 200);
     }
 }