private async Task WebsocketHandler(WebSocket webSocket, User user) { WebSocketPool.Remove(user); WebSocketPool.Add(user, webSocket); _logger.LogInformation($"{user.Username} get connected with WebSocket"); WebSocketReceiveResult result = null; do { var buffer = new byte[1024 * 1]; result = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Text && !result.CloseStatus.HasValue) { user.LastCallTime = DateTime.Now; var msgString = Encoding.UTF8.GetString(buffer); _logger.LogInformation($"user {user.Uid} ReceiveAsync message {msgString}."); WebSocketMessage msg = JsonConvert.DeserializeObject <WebSocketMessage>(msgString); msg.Sender = user; WebSocketRoute(msg); } } while (!result.CloseStatus.HasValue); WebSocketPool.Remove(user); _logger.LogInformation($"{user.Uid} has closed his connection"); }
public Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("heartBeatCheckService started"); Task.Run(() => { while (true) { List <User> userList = WebSocketPool.WebSocketPoolDict.Keys.ToList(); for (int i = userList.Count - 1; i >= 0; i--) { Thread.Sleep(100); User user = userList[i]; TimeSpan timeSpan = DateTime.Now - user.LastCallTime; if (timeSpan.TotalSeconds > 10) { _logger.LogInformation($"websocket of {user.Uid} has been removed"); WebSocketPool.Remove(user); } } Thread.Sleep(10000); } }); return(Task.CompletedTask); }