コード例 #1
0
        private async Task ReadMessageAsync
            (WebSocketReceiveResult result, byte[] buffer,
            MariBaseWebSocketService service, MariWebSocket socket, HttpContext context)
        {
            if (!result.EndOfMessage)
            {
                return;
            }

            _logger.LogTrace($"Incoming WebSocket message from " +
                             $"{context.Connection.RemoteIpAddress}:{context.Connection.RemotePort}.");
            _logger.LogDebug($"Received WebSocket message from client's id: {socket.Id}");

            if (result.MessageType.Equals(WebSocketMessageType.Text))
            {
                await service.OnMessageAsync(socket, Encoding.UTF8.GetString(buffer))
                .Try(_logger, service, socket, false);
            }
            else if (result.MessageType.Equals(WebSocketMessageType.Close))
            {
                _logger.LogTrace($"Incoming WebSocket disconnect from " +
                                 $"{context.Connection.RemoteIpAddress}:{context.Connection.RemotePort}.");
                _logger.LogDebug($"WebSocket with id {socket.Id} disconnected.");

                await service.OnDisconnectedAsync(
                    socket, result.CloseStatus.Value, Encoding.UTF8.GetString(buffer))
                .Try(_logger, service, socket, false);

                service.RemoveClient(socket);

                await socket.WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure,
                                                  "Closed by remote", service.Cts.Token)
                .Try(_logger, service, socket, false);

                socket.Dispose();
            }
        }