想要将标准IO流绑定到TCP流(工作前):
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);
}
}
}我也想在多线程中这样做:不工作:
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);
}我知道一个线程持有一个锁,所以我无法访问另一个线程上的锁。我是生疏的,所以需要知道最好的方法
例:我在GoLang上也是这样做的
func main() {
c, _ := net.Dial("tcp", ":1912")
go io.Copy(os.Stdout, c)
io.Copy(c, os.Stdin)
}发布于 2022-08-24 14:00:29
使用无性系获取流的第二个副本。
为基础套接字创建一个独立的新句柄。 返回的
TcpStream是对此对象引用的相同流的引用。两个句柄将读取和写入相同的数据流,在一个流上设置的选项将传播到另一个流。
然后,您不需要Arc或Mutex -您可以将第二个副本移动到生成的线程中。
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");
}https://stackoverflow.com/questions/73474382
复制相似问题