Hi!
I’m trying to build a TCP server which would broadcast the same message to multiple clients.
This is how I would approach it normally:
- Have a ‘Connection’ type which would hold the connection information
- Have a list of connections where I would push new connections
- Iterate over connection list and send messages to every connection
Here is my attempt of doing it:
Connection struct and a list of connections:
struct Connection {
sender: channel::Sender<String>,
id: usize
}
fn main() -> io::Result<()> {
let mut connections: Vec<Connection> = Vec::new();
Sending messages in a loop to all of the clients:
thread::spawn(move|| {
loop {
for i in 1..1000 {
for connection in connections.iter() {
println!("DEBUG messages in the channel {:?}", connection.sender.len());
connection.sender.send(format!("Test message {}", i));
}
thread::sleep(time::Duration::from_millis(500));
}
}
});
Attempt to add a new connection to the list:
let listener = TcpListener::bind("0.0.0.0:9999")?;
let mut client_count = 0;
for stream in listener.incoming() {
client_count += 0;
let (s, r) = channel::unbounded();
let connection = Connection {
sender: s,
id: client_count
};
connections.push(connection); // use of moved value `connections`
thread::spawn(|| {
handle_client(stream.unwrap(), r);
});
}
I vaguely understand that connections
is in different scope because it’s been used first in for connection in connections.iter() {
which is inside of thread::spawn
. Is my understanding correct?
Anyway, I’m completely lost in how could I fix it or use a different approach to achieve a similar result?
Could someone provide me guidance on how would I do that?
Cheers,
Leonti