public WebSocketMiddleware(RequestDelegate requestDelegate,
                            IWebSocketConnectionHandler handler,
                            string path
                            )
 {
     _next    = requestDelegate;
     _handler = handler;
     _path    = path;
 }
Пример #2
0
 public WebSocketApp(Func <IWebSocketConnectionHandler> createConnectionHandler, string address = "127.0.0.1", int port = 5555)
 {
     this.createConnectionHandler = createConnectionHandler;
     handler      = this.createConnectionHandler();
     this.address = address;
     this.port    = port;
     this.cancellationTokenSource = new CancellationTokenSource();
     _msgQueue = ConnectionFactory.CreateLogicService();
     this._ws  = new WebSocketServer();
     if (_ws.Setup(this.port))
     {
         _ws.Start();
     }
     _ws.NewSessionConnected += OnClientConnected;
     _ws.NewMessageReceived  += OnMessageReceived;
     _ws.NewDataReceived     += OnDataReceivedAsync;
     _ws.SessionClosed       += OnClientClosed;
     //  _timerMsgQueue = new Timer(new TimerCallback(GetMsg), this, 0, 800);
 }
Пример #3
0
        private async Task <bool> ProcessConnectionAsync(
            CancellationToken cancellationToken,
            HttpListenerContext httpContext)
        {
            WebSocketContext webSocketContext = null;

            try
            {
                webSocketContext = await httpContext.AcceptWebSocketAsync(null);
            }
            catch
            {
                httpContext.Response.StatusCode = 500;
                httpContext.Response.Close();
                return(false);
            }
            WebSocket    webSocket = webSocketContext.WebSocket;
            MemoryStream ms        = new MemoryStream();
            IWebSocketConnectionHandler handler = this.createConnectionHandler();

            byte[] receiveBuffer = null;
            while (webSocket.State == WebSocketState.Open)
            {
                if (receiveBuffer == null)
                {
                    receiveBuffer = new byte[MaxBufferSize];
                }
                WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), cancellationToken);

                if (receiveResult.MessageType == WebSocketMessageType.Close)
                {
                    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", cancellationToken);

                    continue;
                }
                if (receiveResult.EndOfMessage)
                {
                    await ms.WriteAsync(receiveBuffer, 0, receiveResult.Count, cancellationToken);

                    receiveBuffer = ms.ToArray();
                    ms.Dispose();
                    ms = new MemoryStream();
                }
                else
                {
                    await ms.WriteAsync(receiveBuffer, 0, receiveResult.Count, cancellationToken);

                    continue;
                }
                byte[] wsresponse = null;
                try
                {
                    wsresponse = await handler.ProcessWsMessageAsync(receiveBuffer, cancellationToken);
                }
                catch (Exception ex)
                {
                    wsresponse = await new ProtobufWsSerializer().SerializeAsync(
                        new WsResponseMessage
                    {
                        Result = WsResult.Error,
                        Value  = Encoding.UTF8.GetBytes(ex.Message)
                    });
                }

                await webSocket.SendAsync(
                    new ArraySegment <byte>(wsresponse),
                    WebSocketMessageType.Binary,
                    true,
                    cancellationToken);
            }
            return(true);
        }
        private async Task <bool> ProcessConnectionAsync(
            CancellationToken cancellationToken,
            HttpListenerContext httpContext)
        {
            Logger.Debug("ProcessConnectionAsync");

            WebSocketContext webSocketContext = null;

            try
            {
                webSocketContext = await httpContext.AcceptWebSocketAsync(null);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "AcceptWebSocketAsync");

                // The upgrade process failed somehow. For simplicity lets assume it was a failure on the part of the server and indicate this using 500.
                httpContext.Response.StatusCode = 500;
                httpContext.Response.Close();
                return(false);
            }

            WebSocket    webSocket = webSocketContext.WebSocket;
            MemoryStream ms        = new MemoryStream();

            try
            {
                IWebSocketConnectionHandler handler = this.createConnectionHandler();

                byte[] receiveBuffer = null;

                // While the WebSocket connection remains open run a simple loop that receives data and sends it back.
                while (webSocket.State == WebSocketState.Open)
                {
                    try
                    {
                        if (receiveBuffer == null)
                        {
                            receiveBuffer = new byte[MaxBufferSize];
                        }

                        WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(receiveBuffer), cancellationToken);

                        if (receiveResult.MessageType == WebSocketMessageType.Close)
                        {
                            Logger.Debug("ProcessConnectionAsync: closing websocket");
                            await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "", cancellationToken);

                            continue;
                        }

                        if (receiveResult.EndOfMessage)
                        {
                            await ms.WriteAsync(receiveBuffer, 0, receiveResult.Count, cancellationToken);

                            receiveBuffer = ms.ToArray();
                            ms.Dispose();
                            ms = new MemoryStream();
                        }
                        else
                        {
                            await ms.WriteAsync(receiveBuffer, 0, receiveResult.Count, cancellationToken);

                            continue;
                        }

                        byte[] wsresponse = null;
                        try
                        {
                            // dispatch to App provided function with requested payload
                            wsresponse = await handler.ProcessWsMessageAsync(receiveBuffer, cancellationToken);
                        }
                        catch (Exception ex)
                        {
                            // catch any error in the appAction and notify the client
                            wsresponse = await new ProtobufWsSerializer().SerializeAsync(
                                new WsResponseMessage
                            {
                                Result = WsResult.Error,
                                Value  = Encoding.UTF8.GetBytes(ex.Message)
                            });
                        }

                        // Send Result back to client
                        await webSocket.SendAsync(
                            new ArraySegment <byte>(wsresponse),
                            WebSocketMessageType.Binary,
                            true,
                            cancellationToken);
                    }
                    catch (WebSocketException ex)
                    {
                        Logger.Error(ex, "ProcessConnectionAsync: WebSocketException={0}", webSocket.State);
                    }
                }

                return(true);
            }
            catch (Exception ex)
            {
                Logger.Error(ex, "ProcessConnectionAsync");
                throw;
            }
        }