尝试使用 Rust tokio Framed LinesCodec 写入服务器
Trying to write to a server using Rust tokio Framed LinesCodec
以下代码成功地从我的服务器读取,但是当识别出特定的行命令时,我似乎无法获得正确的语法或语义来写回服务器。我需要创建一个 FramedWriter 吗?我发现的大多数示例都拆分了套接字,但这似乎有点过分了我希望编解码器能够通过提供一些异步写入方法来处理双向 io。感谢任何帮助。
Cargo.toml
[dependencies]
tokio = { version = "0.3", features = ["full"] }
tokio-util = { version = "0.4", features = ["codec"] }
main.rs
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
implements Stream
and Sink
traits. Sink
defines only the bare minimum of low-level sending methods. To get the high-level awaitable methods like send()
and send_all()
, you need to use the 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),
}
}
以下代码成功地从我的服务器读取,但是当识别出特定的行命令时,我似乎无法获得正确的语法或语义来写回服务器。我需要创建一个 FramedWriter 吗?我发现的大多数示例都拆分了套接字,但这似乎有点过分了我希望编解码器能够通过提供一些异步写入方法来处理双向 io。感谢任何帮助。
Cargo.toml
[dependencies]
tokio = { version = "0.3", features = ["full"] }
tokio-util = { version = "0.4", features = ["codec"] }
main.rs
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
implements Stream
and Sink
traits. Sink
defines only the bare minimum of low-level sending methods. To get the high-level awaitable methods like send()
and send_all()
, you need to use the 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),
}
}