Duplicate nick check

This commit is contained in:
Sebastian Lohff 2021-12-30 23:57:03 +01:00
parent ec94d0445e
commit 150c356283
1 changed files with 19 additions and 9 deletions

View File

@ -80,6 +80,9 @@ impl ChatServer {
Ok(())
}
pub fn is_nick_in_use(&self, name: &str) -> bool {
self.user_map.values().any(|client| { client.name == name })
}
}
#[derive(Debug)]
@ -108,16 +111,23 @@ fn handle_client(mut stream: TcpStream, server: Arc<Mutex<ChatServer>>, client_i
// greet and recv nick
write!(writer, "Hello and welcome to RustChat!\nNick: ")?;
let nick = lines.next().ok_or(ChatError::Protocol(String::from("Could not recv nickname")))??;
// FIXME: check for nick name uniqueness
let mut nick;
loop {
nick = lines.next().ok_or(ChatError::Protocol(String::from("Could not recv nickname")))??;
// check for nick name uniqueness
let mut srv = server.lock()?;
if ! srv.is_nick_in_use(&nick) {
// print joined msg and register at server
srv.send_to_all(&format!("* {} has joined the chat", nick))?;
let curr_users = srv.get_user_count();
let users_in_room_msg = if curr_users == 1 { String::from("is 1 user") } else { format!("are {} users", curr_users) };
write!(writer, " *** {}\n *** You are known as {}. There {} in the room.\n", srv.config.greeting_msg, nick, users_in_room_msg)?;
*client_id = Some(srv.register(nick.clone(), writer));
// print joined msg and register at server
server.lock()?.send_to_all(&format!("* {} has joined the chat", nick))?;
let curr_users = server.lock()?.get_user_count();
let users_in_room_msg = if curr_users == 1 { String::from("is 1 user") } else { format!("are {} users", curr_users) };
write!(writer, "Welcome, {}! You can now start to chat! There {} in the room.\n", nick, users_in_room_msg)?;
// server.lock()?.borrow_mut().push(ChatUser::new(nick.clone(), writer));
*client_id = Some(server.lock()?.register(nick.clone(), writer));
break;
}
write!(writer, "This nickname is already in use, please choose another.\nNick: ")?;
}
// read lines
for line in lines {