Exemplo n.º 1
0
        private async Task Handle(WebsocketClient webSocket)
        {
            WebsocketClientCollection.Add(webSocket);
            logger.Info($"Websocket client added.");
            WebSocketReceiveResult result = null;

            do
            {
                var buffer = new byte[1024 * 1];
                //等待接收消息
                result = await webSocket.WebSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None);

                if (result.MessageType == WebSocketMessageType.Text && !result.CloseStatus.HasValue)
                {
                    var msgString = Encoding.UTF8.GetString(buffer);
                    logger.Info($"Websocket client ReceiveAsync message {msgString}.");
                    var message = JsonConvert.DeserializeObject <Message>(msgString);

                    message.SendClientId = message.SendClientId;
                    MessageRoute(message);
                }
            }while (!result.CloseStatus.HasValue);
            WebsocketClientCollection.Remove(webSocket);
            logger.Info($"Websocket client closed.");
        }
Exemplo n.º 2
0
        public async Task Invoke(HttpContext context)
        {
            if (context.Request.Path == "/ws")
            {
                if (context.WebSockets.IsWebSocketRequest)
                {
                    WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();

                    //从session中获取当前登录用户Id
                    string clientId = CurrentUser.UserId;
                    var    wsClient = new WebsocketClient
                    {
                        Id        = clientId,
                        WebSocket = webSocket
                    };
                    try
                    {
                        await Handle(wsClient);
                    }
                    catch (Exception ex)
                    {
                        logger.Error($"Echo websocket client {clientId} err .", ex);
                        await context.Response.WriteAsync("closed");
                    }
                }
                else
                {
                    context.Response.StatusCode = 404;
                }
            }
            else
            {
                await _next(context);
            }
        }
Exemplo n.º 3
0
 public static void Remove(WebsocketClient client)
 {
     _clients.Remove(client);
 }
Exemplo n.º 4
0
 public static void Add(WebsocketClient client)
 {
     _clients.Add(client);
 }