Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用Tokio';什么是TcpStream?_Tcp_Rust_Rust Tokio - Fatal编程技术网

如何使用Tokio';什么是TcpStream?

如何使用Tokio';什么是TcpStream?,tcp,rust,rust-tokio,Tcp,Rust,Rust Tokio,我正在尝试在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::TcpStre

我正在尝试在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;
    }
}
extern板条箱字节;
外部板条箱期货;
外部板条箱东京大学核心;
外部板条箱东京;
使用self::bytes::BytesMut;
使用self::futures::{Future,Poll,Stream};
使用self::tokio_core::net::TcpStream;
使用self::tokio_堆芯::反应堆::堆芯;
使用self::tokio_io::AsyncRead;
使用std::io;
#[衍生(默认)]
发布结构TcpClient{}
结构AsWeGetIt(R);
AsWeGetIt的impl流
哪里
R:AsyncRead,
{
类型项=字节数;
类型错误=io::错误;
fn轮询(&mut self)->轮询{
设mut buf=BytesMut::具有_容量(1000);
self.0
.read_buf(&mut buf)
.map(| async | async.map(| | Some(buf)))
}
}
impl-TcpClient{
pub fn new()->Self{
自{}
}
发布fn connecttotcserver(&mut self)->bool{
让mut core=core::new().unwrap();
让handle=core.handle();
let address=“127.0.0.1:2323”。parse().expect(“无法解析地址”);
let connection=TcpStream::connect(&地址,&句柄);
让客户端=连接
.然后(| tcp|u流|{
AsWeGetIt(tcp_流)。对于每个(buf){
println!(“{:?}”,buf);
好(())
})
})
.map|u err(| e | eprintln!(“错误:{},e));
core.run(client.expect(“无法运行事件循环”);
返回true;
}
}

如何添加异步数据发送功能?

如果希望在套接字上有两个完全独立的数据流,可以在当前版本的Tokio中使用
TcpStream
上的方法:

let connection = TcpStream::connect(&address);
connection.and_then(|socket| {
    let (rx, tx) = socket.split();
    //Independently use tx/rx for sending/receiving
    return Ok(());
});
拆分后,您可以单独使用
rx
(接收端)和
tx
(发送端)。下面是一个将发送和接收视为完全独立的小示例。发送方只需定期发送相同的消息,而接收方只需打印所有输入数据:

extern crate futures;
extern crate tokio;

use self::futures::{Future, Poll, Stream};
use self::tokio::net::TcpStream;
use tokio::io::{AsyncRead, AsyncWrite, Error, ReadHalf};
use tokio::prelude::*;
use tokio::timer::Interval;

//Receiver struct that implements the future trait
//this exclusively handles incomming data and prints it to stdout
struct Receiver {
    rx: ReadHalf<TcpStream>, //receiving half of the socket stream
}
impl Future for Receiver {
    type Item = ();
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let mut buffer = vec![0u8; 1000]; //reserve 1000 bytes in the receive buffer
                                          //get all data that is available to us at the moment...
        while let Async::Ready(num_bytes_read) = self.rx.poll_read(&mut buffer)? {
            if num_bytes_read == 0 {
                return Ok(Async::Ready(()));
            } //socket closed
            print!("{}", String::from_utf8_lossy(&buffer[..num_bytes_read]));
        }
        return Ok(Async::NotReady);
    }
}

fn main() {
    let address = "127.0.0.1:2323".parse().expect("Unable to parse address");
    let connection = TcpStream::connect(&address);
    //wait for the connection to be established
    let client = connection
        .and_then(|socket| {
            //split the successfully connected socket in half (receive / send)
            let (rx, mut tx) = socket.split();

            //set up a simple sender, that periodically (1sec) sends the same message
            let sender = Interval::new_interval(std::time::Duration::from_millis(1000))
                .for_each(move |_| {
                    //this lambda is invoked once per passed second
                    tx.poll_write(&vec![82, 117, 115, 116, 10]).map_err(|_| {
                        //shut down the timer if an error occured (e.g. socket was closed)
                        tokio::timer::Error::shutdown()
                    })?;
                    return Ok(());
                }).map_err(|e| println!("{}", e));
            //start the sender
            tokio::spawn(sender);

            //start the receiver
            let receiver = Receiver { rx };
            tokio::spawn(receiver.map_err(|e| println!("{}", e)));

            return Ok(());
        }).map_err(|e| println!("{}", e));

    tokio::run(client);
}
extern板条箱期货;
外部板条箱东京;
使用self::futures::{Future,Poll,Stream};
使用self::tokio::net::TcpStream;
使用tokio::io::{AsyncRead,AsyncWrite,Error,ReadHalf};
使用东京::前奏::*;
使用tokio::timer::Interval;
//实现未来特性的Receiver结构
//它专门处理输入数据并将其打印到标准输出
结构接收器{
rx:ReadHalf,//接收套接字流的一半
}
接收机的impl未来{
类型项=();
类型错误=错误;
fn轮询(&mut self)->轮询{
让mut buffer=vec![0u8;1000];//在接收缓冲区中保留1000字节
//获取我们目前可用的所有数据。。。
而让Async::Ready(num\u bytes\u read)=self.rx.poll\u read(&mut buffer){
如果num_bytes_read==0{
返回Ok(异步::就绪(());
}//套接字已关闭
打印!(“{}”,字符串::from_utf8_lossy(&buffer[…num_bytes_read]);
}
返回Ok(异步::NotReady);
}
}
fn main(){
let address=“127.0.0.1:2323”。parse().expect(“无法解析地址”);
let connection=TcpStream::connect(&address);
//等待建立连接
让客户端=连接
.然后(|插座|{
//将成功连接的套接字一分为二(接收/发送)
let(rx,mut-tx)=socket.split();
//设置一个简单的发送器,定期(1秒)发送相同的消息
let sender=Interval::new_Interval(std::time::Duration::from_millis(1000))
.为每个人(移动| |{
//此lambda每秒调用一次
tx.poll_write(&vec![821171111116,10]).map_err(| |{
//如果发生错误(例如,套接字已关闭),请关闭计时器
东京::定时器::错误::关机()
})?;
返回Ok(());
}).map|u err(|e|println!(“{}”,e));
//启动发送器
tokio::spawn(发送方);
//启动接收器
设接收器=接收器{rx};
tokio::spawn(receiver.map_err(| e | println!(“{}”,e));
返回Ok(());
}).map|u err(|e|println!(“{}”,e));
东京:运行(客户端);
}
对于某些应用程序,这就足够了。但是,您通常会在连接上定义协议/格式。例如,HTTP连接总是由请求和响应组成,每个请求和响应都由头和主体组成。Tokio没有直接在字节级别上工作,而是提供了适合于套接字的traits
Encoder
Decoder
,它对协议进行解码,并直接提供您想要使用的实体。例如,您可以查看非常基本的或编解码器

当传入消息触发传出消息时,情况会变得更加复杂。对于最简单的情况(每一条传入的消息只会导致一条传出的消息),您可以看看官方的请求/响应示例