rust - Rust Tokio TcpStream 侦听和读取
问题描述
- 所以我从将 a 连接
TcpStream
到IP:Port
. (作品) - 从那里,我创建了一个能够使用此连接发送消息的函数。(作品)
- 然后我尝试添加从套接字读取的功能......(不以相同的方式工作) - 这是我可以使用一些帮助的地方。
代码:
#[derive(Debug, Clone)]
struct Connection {
stream: Arc<Mutex<TcpStream>>,
loc: usize,
}
// 1. Connect Stream to Address and Return Connection to use for later
async fn connect(loc:usize) -> Result<Connection, ConnectionError> {
println!("Connecting");
let mut socket = TcpStream::connect("IP:PORT").await.map_err(|_| ConnectionError::ConnectError(loc))?;
Ok( Connection {
stream: Arc::new(Mutex::new(socket)),
loc: loc,
}
)
}
//2. Get stream from Arc - send message to connection - if there is an error, set to `SendError`
async fn Send(connection: Connection, string: String) -> Result<(), ConnectionError> {
let mut stream = connection.stream.lock().await;
stream.write_all(string.as_bytes()).await.map_err(|_| ConnectionError::SendError(connection.loc))?;
Ok( () )
}
为了从我的初始设置中创建监听部分,我尝试了:
- 拆分流(作品)
- 创建一个线程来生成(工作)
- 返回初始流以便能够执行发送命令(因为我无法克隆/复制 Tokio 线程,所以没有工作)
// 3.
async fn connect(loc:usize) -> Result<Connection, ConnectionError> {
println!("Connecting");
let mut socket = TcpStream::connect("IP:PORT").await.map_err(|_| ConnectionError::ConnectError(loc))?;
let (mut read, mut write) = tokio::io::split(socket);
// I only need to utilize the `read` portion of the stream at this time.
tokio::spawn(async move {
loop {
let mut buf = [0u8; 32];
read.read(&mut buf).await.unwrap();
println!("{:?}", std::str::from_utf8(&buf));
}
});
Ok( Connection {
stream: Arc::new(Mutex::new(socket)), //Error Here
loc: loc,
}
)
}
错误:
error[E0382]: use of moved value: `socket`
--> src\main.rs:312:32
|
299 | let socket = TcpStream::connect("3.85.107.207:80").await.map_err(|_| ConnectionError::ConnectError(loc))?;
| ------ move occurs because `socket` has type `tokio::net::TcpStream`, which does not implement the `Copy` trait
300 |
301 | let (mut rd, mut wr) = tokio::io::split(socket);
| ------ value moved here
...
312 | stream: Arc::new(Mutex::new(socket)),
| ^^^^^^ value used here after move
问题:
我理解 a 的概念,Copy
但未Clone
实现Tokio::TcpStream
;另外,我知道它Tokio::TcpStream
没有try_clone()
像那样实现方法std::TcpStream
,但是我可以实现什么解决方法,所以我可以
- 连接时运行流的读取部分;
- 稍后发送消息,当我准备好发送消息时?
解决方案
推荐阅读
- powershell - 使用 System.Diagnostics.Process 在标准输入上向 Plink 输入 ay?
- python - 更改用户指定目录中的文件名
- r-markdown - 在 blogdown 中使插入的图像适合内容 div
- javascript - JS:Facebook 登录 SDK 不返回电子邮件
- c++ - pair 和 vector 在 Graph 实现中是如何工作的?
- python - Matplotlib:使轴适合形状限制
- ios - Spritekit 动画没有改变
- angular - Angular 6:在同一页面上显示有关所选下拉项目的信息
- ionic-framework - 错误:在“imports”中发现多个 IonicModule.forRoot 调用。只允许一个
- javascript - 如何使用javascript在2种形式之间切换?