Reputation: 39
want to bind the Standard IO stream to TCP stream Working ex:
fn main() {
let mut stream =TcpStream::connect("localhost:1912").unwrap();
let stdin = io::stdin();
for command in stdin.lock().lines() {
{
let mut cmd = command.unwrap();
cmd = cmd.add("\n");
_ = stream.write(cmd.as_bytes()).unwrap();
}
{
let mut resp_data = [0 as u8; 250];
_ = stream.read(&mut resp_data).unwrap();
let text = from_utf8(&resp_data).unwrap();
print!("{}", text);
}
}
}
Same I want to do in multi-thread like : not working:
fn main() {
let stream = Arc::new(Mutex::new(TcpStream::connect("localhost:1912").unwrap()));
let str_clone = stream.clone();
thread::spawn(move || {
let mut stout = io::stdout();
let mut str = str_clone.lock().unwrap();
_ = io::copy(&mut *str, &mut stout);
});
let mut stdin = io::stdin();
let mut str = stream.lock().unwrap();
_ = io::copy(&mut stdin, &mut *str);
}
I know that one thread is holding a lock so I am not able to access this on another thread. I am new to Rust so need to know that best way to do this
Ex: This same I was able to do in GoLang like this
func main() {
c, _ := net.Dial("tcp", ":1912")
go io.Copy(os.Stdout, c)
io.Copy(c, os.Stdin)
}
Upvotes: 1
Views: 1726
Reputation: 6867
Use TcpStream::try_clone to get a second copy of the stream.
Creates a new independently owned handle to the underlying socket.
The returned
TcpStream
is a reference to the same stream that this object references. Both handles will read and write the same stream of data, and options set on one stream will be propagated to the other stream.
Then, you don't need Arc
or Mutex
- you can move the second copy into the spawned thread.
use std::io;
use std::net::TcpStream;
use std::thread;
fn main() {
let mut stream = TcpStream::connect("localhost:1912").unwrap();
let mut stream2 = stream.try_clone().expect("could not clone the stream");
thread::spawn(move || {
let mut stout = io::stdout();
io::copy(&mut stream2, &mut stout).expect("error while reading from the stream");
});
let mut stdin = io::stdin();
io::copy(&mut stdin, &mut stream).expect("error while writing to the stream");
}
Upvotes: 3