以下代码成功地从服务器读取了消息,但是当识别到特定的行命令时,似乎无法获得正确的语法或语义来写回到服务器。我需要创建一个FramedWriter吗?我发现的大多数示例都拆分了套接字,但是这似乎有些过头了,我希望编解码器能够通过提供一些异步写入方法来处理双向io。任何帮助表示赞赏。
货代
[dependencies]
tokio = { version = "0.3", features = ["full"] }
tokio-util = { version = "0.4", features = ["codec"] }
主use tokio::net::{ TcpStream };
use tokio_util::codec::{ Framed, LinesCodec };
use tokio::stream::StreamExt;
use std::error::Error;
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
let saddr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8081);
let conn = TcpStream::connect(saddr).await?;
let mut server = Framed::new(conn, LinesCodec::new_with_max_length(1024));
while let Some(Ok(line)) = server.next().await {
match line.as_str() {
"READY" => println!("Want to write a line to the stream"),
_ => println!("{}", line),
}
}
Ok({})
}
最佳答案
根据documentation,Framed
实现Stream
和Sink
特性。 Sink
仅定义最低限度的发送方法。为了获得诸如send()
和send_all()
之类的高级等待方法,您需要使用 SinkExt
扩展特征。
例如(playground):
use futures::sink::SinkExt;
// ...
while let Some(Ok(line)) = server.next().await {
match line.as_str() {
"READY" => server.send("foo").await?,
_ => println!("{}", line),
}
}
关于rust - 尝试使用Rust tokio Framed LinesCodec写入服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64955922/