Please help me, I want to create a multithreaded server with TCP connections.
How to make it so that the server can transmit data by some asynchronous event with current TCP streams, as well as respond to incoming data streams?
It is not possible to implement this, since the Rust does not allow the mutable TCP stream to be given over to two functions
let listener = TcpListener::bind("127.0.0.1:3000").unwrap();
for stream in listener.incoming() {
match stream {
Ok(mut stream) => {
let receiver = receiver.clone();
thread::spawn( move || {
handle_client(stream)
});
}
Err(e) => {
println!("Error: {}", e);
}
}
}
I tried to use the mpc channel, but the receiver must be mutable for use in the function, and it is not possible to transfer it to each connection handler
ВуDengin is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
&TcpStream
(a reference to TcpStream
) impls Read
, which means that you can share Arc<TcpStream>
and still read/write to it as (&*stream).read(...)
or (&*stream).write(...)
.
Alternatively, clone the stream with try_clone()
.