I have implemented a chat server which stores the connected users and if a user send a message, the server echoes it to all other clients.
I have C++ background so I made a global static mut USERS:Vec<TcpStream>
variable to store and access the users.
I'm handling the connected users from main() like this:
#[async_std::main]
async fn main() -> io::Result<()>{
let listener = TcpListener::bind("127.0.0.1:14530").await?;
loop {
let (stream, addr) = listener.accept().await?;
unsafe {
USERS.push(stream.clone());
}
task::spawn(on_connection(stream, addr));
}
}
and on_connection
function is:
async fn on_connection(mut stream:TcpStream, addr:SocketAddr) -> io::Result<()> {
println!("New Connection: {}", addr.to_string());
let mut buffer = [0u8; 1024];
loop {
let len = stream.read(&mut buffer).await?;
if len > 0 {
print!("Message from {} => {}", addr.to_string(), String::from_utf8_lossy(&buffer));
unsafe {
for mut user in USERS.clone() {
user.write(&buffer).await?;
}
}
}
else {
println!("Disconnected: {}", addr.to_string());
break
}
};
Ok(())
}
Is it okay to use Rust like this?
I want to make the application safe and use Rust's safe environment without "unsafe". But I couldn't work out how to store global users to access later without unsafe.