我正在尝试在 Rust 中实现 TCP 客户端。我能够读取来自服务器的数据,但我无法发送数据。
这是我正在处理的代码:
extern crate bytes;
extern crate futures;
extern crate tokio_core;
extern crate tokio_io;
use self::bytes::BytesMut;
use self::futures::{Future, Poll, Stream};
use self::tokio_core::net::TcpStream;
use self::tokio_core::reactor::Core;
use self::tokio_io::AsyncRead;
use std::io;
#[derive(Default)]
pub struct TcpClient {}
struct AsWeGetIt<R>(R);
impl<R> Stream for AsWeGetIt<R>
where
R: AsyncRead,
{
type Item = BytesMut;
type Error = io::Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
let mut buf = BytesMut::with_capacity(1000);
self.0
.read_buf(&mut buf)
.map(|async| async.map(|_| Some(buf)))
}
}
impl TcpClient {
pub fn new() -> Self {
Self {}
}
pub fn connectToTcpServer(&mut self) -> bool {
let mut core = Core::new().unwrap();
let handle = core.handle();
let address = "127.0.0.1:2323".parse().expect("Unable to parse address");
let connection = TcpStream::connect(&address, &handle);
let client = connection
.and_then(|tcp_stream| {
AsWeGetIt(tcp_stream).for_each(|buf| {
println!("{:?}", buf);
Ok(())
})
})
.map_err(|e| eprintln!("Error: {}", e));
core.run(client).expect("Unable to run the event loop");
return true;
}
}
如何添加异步数据发送功能?