The current issue that I am having is creating a way to reference the TCPListener from a thread into the Struct of the main thread. The end goal of what I am trying to accomplish is a way to reference the server's TCP connections from the Server struct.
Here is the code:
use std::io::Read;
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, mpsc, Mutex};
use std::thread;
fn main() {
let server = Server::start("127.0.0.1:25565".to_string());
loop {
for client in server.connected_clients {
println!("{:?}", client.stream.peer_addr().unwrap())
}
}
}
#[derive(Debug)]
struct Server {
listener: Arc<Mutex<TcpListener>>,
connected_clients: Vec<Client>,
}
impl Server {
pub fn start(address: String) -> Server {
let listener = TcpListener::bind(address).unwrap();
let (tx, rx) = mpsc::channel();
let listener = Arc::new(Mutex::new(listener));
let server = Server {
listener: listener,
connected_clients: Vec::new()
};
tx.send(&server.listener).unwrap();
thread::spawn(|| {
let listener = rx.recv().unwrap();
// For each new connection start a new thread
for stream in listener.lock().unwrap().incoming() {
let mut stream = stream.unwrap();
thread::spawn(move || {
// TODO: Add client to the connected_clients Vec
let mut buffer = [0; 1024];
loop {
stream.read(&mut buffer).unwrap();
println!("{}", String::from_utf8(Vec::from(&buffer[..])).unwrap().trim_end_matches(char::from(0)));
}
});
}
});
server
}
}
#[derive(Debug)]
struct Client {
id: usize,
stream: TcpStream,
}
ERROR: std::sync::mpsc::Receiver<&Arc<Mutex>>` cannot be shared between threads safely