예제 #1
0
        public async Task ReceiveMessagesUntilCloseAsync_And_Exit()
        {
            var fakeSocket       = new FakeWebSocket();
            var socketConnection = new WebSocketConnection(fakeSocket);

            var message = "";

            socketConnection.ReceiveText += (sender, s) =>
            {
                message = s;
            };

            // when this unit test keeps hanging the end signal has not passed correctly
            await socketConnection.ReceiveMessagesUntilCloseAsync();

            Assert.IsTrue(message.StartsWith("message"));
        }
        public async Task CreateWebSocketConnectionAsync(WebSocket webSocket,
                                                         WebSocketConnectionsOptions options,
                                                         Guid connectionId)
        {
            WebSocketConnection webSocketConnection = new WebSocketConnection(webSocket,
                                                                              options.ReceivePayloadBufferSize, connectionId);

            webSocketConnection.ReceiveText += OnReceiveText;
            OnConnect(webSocketConnection);

            await webSocketConnection.ReceiveMessagesUntilCloseAsync();

            if (webSocketConnection.CloseStatus.HasValue)
            {
                await webSocket.CloseAsync(webSocketConnection.CloseStatus.Value, webSocketConnection.CloseStatusDescription, CancellationToken.None);
            }
            Disconnect?.Invoke(this, webSocketConnection);
            webSocketConnection.ReceiveText -= OnReceiveText;
        }
        public async Task Invoke(HttpContext context)
        {
            if (context.WebSockets.IsWebSocketRequest)
            {
                if (ValidateOrigin(context))
                {
                    var textSubProtocol = NegotiateSubProtocol(context.WebSockets.WebSocketRequestedProtocols);
                    var webSocketCompressionProvider = _compressionService.NegotiateCompression(context);
                    var webSocket = await context.WebSockets.AcceptWebSocketAsync(textSubProtocol?.SubProtocol);

                    var webSocketConnection = new WebSocketConnection(webSocket, webSocketCompressionProvider, textSubProtocol ?? _options.DefaultSubProtocol, _options.ReceivePayloadBufferSize);

                    webSocketConnection.ReceiveText += async(sender, message) =>
                    {
                        await webSocketConnection.SendAsync(message, CancellationToken.None);
                    };

                    _connectionsService.AddConnection(webSocketConnection);

                    await webSocketConnection.ReceiveMessagesUntilCloseAsync();

                    if (webSocketConnection.CloseStatus.HasValue)
                    {
                        await webSocket.CloseAsync(webSocketConnection.CloseStatus.Value, webSocketConnection.CloseStatusDescription, CancellationToken.None);
                    }

                    _connectionsService.RemoveConnection(webSocketConnection.Id);
                }
                else
                {
                    context.Response.StatusCode = StatusCodes.Status403Forbidden;
                }
            }
            else
            {
                context.Response.StatusCode = StatusCodes.Status400BadRequest;
            }
        }
예제 #4
0
        public async Task Invoke(HttpContext context)
        {
            if (!context.WebSockets.IsWebSocketRequest)
            {
                await _next.Invoke(context); // can we have a request to the same path and not for a WS connection? Consider using the code on the next line

                //context.Response.StatusCode = StatusCodes.Status400BadRequest;
                return;
            }

            var webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);

            var webSocketConnection = new WebSocketConnection(webSocket);

            _connectionsService.AddConnection(webSocketConnection);

            await webSocketConnection.ReceiveMessagesUntilCloseAsync();

            //await Receive(webSocket, /*async*/ (result, serializedMessage) =>
            //{
            //    if (result.MessageType == WebSocketMessageType.Text)
            //    {
            //        //Message message = JsonConvert.DeserializeObject<Message>(serializedMessage, _jsonSerializerSettings);
            //        //await _webSocketHandler.ReceiveAsync(socket, result, message).ConfigureAwait(false);
            //        return;
            //    }
            //});

            if (webSocketConnection.CloseStatus.HasValue)
            {
                // the close handshake shouldn't be completed on prematurely closed connections
                await webSocket.CloseAsync(webSocketConnection.CloseStatus.Value, webSocketConnection.CloseStatusDescription, CancellationToken.None);
            }

            _connectionsService.RemoveConnection(webSocketConnection.Id);
        }
        public async Task Invoke(HttpContext context)
        {
            if (ValidateOrigin(context))
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                    if (!context.User.Identity.IsAuthenticated)
                    {
                        // Status Code 1008 PolicyViolation
                        await webSocket.CloseOutputAsync(WebSocketCloseStatus.PolicyViolation,
                                                         "Please login first", CancellationToken.None);

                        return;
                    }

                    WebSocketConnection webSocketConnection = new WebSocketConnection(webSocket, _options.ReceivePayloadBufferSize);

                    async void OnWebSocketConnectionOnNewConnection(object sender, EventArgs message)
                    {
                        await Task.Delay(150);

                        try
                        {
                            var welcomeMessage = new ApiNotificationResponseModel <HeartbeatModel>(new HeartbeatModel(null))
                            {
                                Type = ApiNotificationType.Welcome,
                            };
                            await webSocketConnection.SendAsync(JsonSerializer.Serialize(welcomeMessage,
                                                                                         DefaultJsonSerializer.CamelCase), CancellationToken.None);
                        }
                        catch (WebSocketException)
                        {
                            // if the client is closing the socket the wrong way
                        }
                    }

                    webSocketConnection.NewConnection += OnWebSocketConnectionOnNewConnection;

                    _connectionsService.AddConnection(webSocketConnection);

                    await webSocketConnection.ReceiveMessagesUntilCloseAsync();

                    if (webSocketConnection.CloseStatus.HasValue)
                    {
                        await webSocket.CloseOutputAsync(webSocketConnection.CloseStatus.Value,
                                                         webSocketConnection.CloseStatusDescription, CancellationToken.None);
                    }

                    _connectionsService.RemoveConnection(webSocketConnection.Id);
                }
                else
                {
                    context.Response.StatusCode = StatusCodes.Status400BadRequest;
                }
            }
            else
            {
                context.Response.StatusCode = StatusCodes.Status403Forbidden;
            }
        }