async Task IWebSocketConnection.HandleMessagesAsync(IWebSocket socket, CancellationToken cancellation)
        {
            WebSocket = socket;
            _connectionManager.AddSession(this);
            await OnConnected();

            bool onDisconnectedInvoked = false;

            while (WebSocket.WebSocketState == JsonRpcWebSocketState.Open)
            {
                var(type, buffer) = await WebSocket.ReceiveAsync(cancellation);

                string message = null;
                if (buffer.Array == null)
                {
                    _connectionManager.RemoveSession(this);
                    const int invalidPayloadData = 1007;
                    await WebSocket.CloseAsync(invalidPayloadData, "Received empty data buffer");

                    throw new InvalidOperationException("Received empty data buffer from underlying socket");
                }
                if (type != MessageType.Binary)
                {
                    message = Encoding.UTF8.GetString(buffer.Array, buffer.Offset, buffer.Count);
                }

                if (type == MessageType.Text)
                {
                    await OnMessage(message);
                }
                else if (type == MessageType.Binary)
                {
                    await OnBinaryMessage(buffer);
                }
                else if (type == MessageType.Close)
                {
                    await OnDisconnected(CloseStatusCode.Normal, message);

                    onDisconnectedInvoked = true;
                    break;
                }
                else
                {
                    throw new ArgumentOutOfRangeException();
                }
            }

            _connectionManager.RemoveSession(this);
            if (!onDisconnectedInvoked)
            {
                await OnDisconnected(CloseStatusCode.Normal, "Socket closed");
            }
        }
Ejemplo n.º 2
0
        protected override Task OnDisconnected(CloseStatusCode code, string reason)
        {
            _connectionManager.RemoveSession(this);
//			_connectionManager.Remove(ID);
//
//			JsonRpcWebSocketServiceEventSource.Log.ConnectionClosed(ID, GetType().Name);
            return(Task.CompletedTask);
        }