Duplicate nick check
This commit is contained in:
parent
ec94d0445e
commit
150c356283
26
src/main.rs
26
src/main.rs
|
@ -80,6 +80,9 @@ impl ChatServer {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn is_nick_in_use(&self, name: &str) -> bool {
|
||||||
|
self.user_map.values().any(|client| { client.name == name })
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
@ -108,16 +111,23 @@ fn handle_client(mut stream: TcpStream, server: Arc<Mutex<ChatServer>>, client_i
|
||||||
|
|
||||||
// greet and recv nick
|
// greet and recv nick
|
||||||
write!(writer, "Hello and welcome to RustChat!\nNick: ")?;
|
write!(writer, "Hello and welcome to RustChat!\nNick: ")?;
|
||||||
let nick = lines.next().ok_or(ChatError::Protocol(String::from("Could not recv nickname")))??;
|
let mut nick;
|
||||||
// FIXME: check for nick name uniqueness
|
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
|
// print joined msg and register at server
|
||||||
server.lock()?.send_to_all(&format!("* {} has joined the chat", nick))?;
|
srv.send_to_all(&format!("* {} has joined the chat", nick))?;
|
||||||
let curr_users = server.lock()?.get_user_count();
|
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) };
|
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)?;
|
write!(writer, " *** {}\n *** You are known as {}. There {} in the room.\n", srv.config.greeting_msg, nick, users_in_room_msg)?;
|
||||||
// server.lock()?.borrow_mut().push(ChatUser::new(nick.clone(), writer));
|
*client_id = Some(srv.register(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
|
// read lines
|
||||||
for line in lines {
|
for line in lines {
|
||||||
|
|
Loading…
Reference in New Issue