/// <summary> /// Accept a new user, search a free user name and inform the other users /// </summary> /// <param name="socket"></param> /// <param name="socketId"></param> /// <returns></returns> private async Task AcceptNewUser(WebSocket socket, string socketId) { ChatPartner newChatPartner = new ChatPartner() { WebSocket = socket, }; lock (_sockets) { newChatPartner.Nickname = GetFreeNickname("anonymous"); newChatPartner.Identifier = socketId; _sockets.TryAdd(socketId, newChatPartner); } _globalRoom.ConnectedUsers.Add(newChatPartner.Identifier); UserJoinMessage joinMessage = new UserJoinMessage() { SenderGuid = socketId, IsOriginOfMessage = false, ChatUser = newChatPartner }; await InformUsersAboutJoin(joinMessage, _globalRoom); }
/// <summary> /// Inform all users about a joining user /// </summary> /// <param name="message"></param> /// <returns></returns> private async Task InformUsersAboutJoin(UserJoinMessage message, ChatRoom targetRoom) { //send the joining user his user name and all other users that he joined the server await Task.WhenAll(targetRoom.ConnectedUsers.Select(userKey => { if (_sockets.TryGetValue(userKey, out ChatPartner user)) { message.IsOriginOfMessage = user.Identifier == message.SenderGuid; string serialized = JsonConvert.SerializeObject(message, Global.SerializerSettings); return(SendStringAsync(user.WebSocket, user.Identifier, serialized, CancellationToken.None)); } return(Task.CompletedTask); }).ToArray()); }
/// <summary> /// Handles the room join request of a user and adds him to the room if the password is correct /// </summary> /// <param name="joinRequest"></param> /// <returns></returns> private async Task HandleRoomJoinRequest(RoomJoinRequest joinRequest) { //send the user the result of his request (helper method to avoid duplicate code9 async Task sendRequestResult(bool success) { //send the user a message back that the password was wrong if (_sockets.TryGetValue(joinRequest.SenderGuid, out ChatPartner user)) { joinRequest.IsSuccessful = success; string serialized = JsonConvert.SerializeObject(joinRequest, Global.SerializerSettings); await SendStringAsync(user.WebSocket, user.Identifier, serialized, CancellationToken.None); } } //check if the room exists and if the correct password is supplied (if the room is password protected) if (_chatrooms.TryGetValue(joinRequest.RoomIdentifier, out ChatRoom joinRoom)) { if ((!joinRoom.IsPasswordProtected || joinRoom.Password == joinRequest.Password) && !joinRoom.ConnectedUsers.Contains(joinRequest.SenderGuid)) { joinRoom.ConnectedUsers.Add(joinRequest.SenderGuid); var joinMessage = new UserJoinMessage() { SenderGuid = joinRequest.SenderGuid, RoomIdentifier = joinRequest.RoomIdentifier, Timestamp = DateTime.Now }; await sendRequestResult(true); await InformUsersAboutJoin(joinMessage, joinRoom); } else { await sendRequestResult(false); } } }