首页 > 解决方案 > Rust Tokio TcpStream 侦听和读取

问题描述

  1. 所以我从将 a 连接TcpStreamIP:Port. (作品)
  2. 从那里,我创建了一个能够使用此连接发送消息的函数。(作品)
  3. 然后我尝试添加从套接字读取的功能......(不以相同的方式工作) - 这是我可以使用一些帮助的地方。

代码:

#[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( () )
}

为了从我的初始设置中创建监听部分,我尝试了:

  1. 拆分流(作品)
  2. 创建一个线程来生成(工作)
  3. 返回初始流以便能够执行发送命令(因为我无法克隆/复制 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,但是我可以实现什么解决方法,所以我可以

  1. 连接时运行流的读取部分;
  2. 稍后发送消息,当我准备好发送消息时?

标签: rustrust-tokio

解决方案


推荐阅读