/// <summary> /// Inform all users that a specific user has left a room/the server /// </summary> /// <param name="useridentifier"></param> /// <returns></returns> private async Task InformServerAboutLeavingUser(UserLeaveMessage message) { if (_chatrooms.TryGetValue(message.RoomIdentifier, out ChatRoom room)) { string serialized = JsonConvert.SerializeObject(message, Global.SerializerSettings); await SendMessageIntoRoom(room, serialized); } }
/// <summary> /// Closes the user's websocket, removes him from the server and informs the other users that he is disconnected /// </summary> /// <param name="userIdentifier"></param> /// <returns></returns> public async Task DisconnectUserFromServer(string userIdentifier) { bool proceedWithDisconnect = false; ChatPartner user = null; lock (_userRemovalLockObject) { //the socket still has to be in our socket-dictionary and shouldn't be in the list of currently disconnecting users if (_sockets.TryRemove(userIdentifier, out user) && !_queuedUsersToDisconnect.Contains(userIdentifier)) { _queuedUsersToDisconnect.Add(userIdentifier); proceedWithDisconnect = true; } else { _queuedUsersToDisconnect.Remove(userIdentifier); } } if (proceedWithDisconnect) { try { await RemoveUserFromAllChatRooms(userIdentifier); Task closeTask = user.WebSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Closing", CancellationToken.None); closeTask.Wait(); user.WebSocket.Dispose(); } catch (Exception ex) { //catch errors (if the closing of the socket fails) } UserLeaveMessage message = new UserLeaveMessage() { RoomIdentifier = _globalRoom.RoomIdentifier, SenderGuid = userIdentifier }; await InformServerAboutLeavingUser(message); lock (_userRemovalLockObject) { _queuedUsersToDisconnect.Remove(userIdentifier); } } }
/// <summary> /// Handles the action that a user leaves a room /// </summary> /// <param name="message"></param> /// <returns></returns> private async Task HandleUserLeavingRoom(UserLeaveMessage message) { ChatRoom room = _chatrooms[message.RoomIdentifier]; //remove user from the room lock (_userRemovalLockObject) { room.ConnectedUsers.Remove(message.SenderGuid); } //delete the room if it's empty (the global room can't be removed) //if (room.RoomIdentifier != 0 && room.ConnectedUsers.Count == 0) //{ // lock(_userRemovalLockObject) // { // _chatrooms.TryRemove(room.RoomIdentifier, out ChatRoom dummy); // } //} await InformServerAboutLeavingUser(message); }