Skip to content

Instantly share code, notes, and snippets.

@UlisseMini
Created April 24, 2019 03:31
Show Gist options
  • Save UlisseMini/181a277975422fb8ecfcf7cfde204e2b to your computer and use it in GitHub Desktop.
Save UlisseMini/181a277975422fb8ecfcf7cfde204e2b to your computer and use it in GitHub Desktop.
fn main() {
let mut clients = vec![]
.push(stream1)
.push(stream2)
.push(stream3);
for client in &clients {
if client.can_recv() {
// now i want to send this message to every connectede
// client. and if there is an error i want to
// remove the client from the vector, it won't let me though
// becauses clients is borrowed.
for person_to_send_to in &clients {
person_to_send_to.send(client.data());
if send_failed {
remove(person_to_send_to, from(clients))
}
}
}
}
}
use std::io::{ErrorKind, Read, Write};
use std::net::TcpListener;
use std::thread;
const BIND_ADDR: &str = "127.0.0.1:1337";
const MAX_MSG_SIZE: usize = 32;
fn sleep() {
thread::sleep(::std::time::Duration::from_millis(100));
}
fn main() -> Result<(), std::io::Error> {
let server = TcpListener::bind(BIND_ADDR)?;
server.set_nonblocking(true)?;
let mut clients = vec![];
loop {
// if let Ok((mut socket, addr)) = server.accept() {
let _ = server.accept().map(|(mut socket, addr)| {
println!("Client {} connected", addr);
let _ = socket
.set_nonblocking(true)
.map_err(|e| println!("{}", e))
.map(|_| match socket.try_clone() {
Ok(c) => clients.push(c),
Err(err) => {
println!("Failed to clone client: {}", err);
return;
}
});
});
for mut socket in &clients {
let mut buf = vec![0; MAX_MSG_SIZE];
match socket.read(&mut buf) {
Ok(_) => {
let msg = buf.into_iter().take_while(|&x| x != 0).collect::<Vec<_>>();
if msg.is_empty() {
println!("EOF");
break;
}
let msg = String::from_utf8(msg).expect("Invalid utf8 message");
println!("{:?}", msg);
// cannot move out of `clients` because it is borrowed
clients = clients
.into_iter()
.filter_map(|mut client| {
let mut buf = msg.clone().into_bytes();
buf.resize(MAX_MSG_SIZE, 0);
client.write_all(&buf).map(|_| client).ok()
})
.collect::<Vec<_>>();
}
Err(ref err) if err.kind() == ErrorKind::WouldBlock => (),
Err(err) => {
println!("Close {}", err);
break;
}
}
}
sleep();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment