mio中缓冲区类型的问题

时间:2015-10-24 07:53:42

标签: rust mio

我想使用mio在Rust中编写异步服务器,但我遇到了缓冲区类型问题。我尝试过不同的缓冲区类型,无法让它工作。我目前的代码是:

extern crate mio;
extern crate bytes;

use std::io;
use std::io::{Error, ErrorKind};
use std::net::SocketAddr;
use std::str::FromStr;
use std::io::Cursor;

use self::mio::PollOpt;
use self::mio::EventLoop;
use self::mio::EventSet;
use self::mio::Token;
use self::mio::Handler;
use self::mio::io::TryRead;
use self::mio::io::TryWrite;
//use self::mio::buf::ByteBuf;
//use self::mio::buf::Buf;
use self::mio::tcp::*;
use self::bytes::buf::Buf;
use self::bytes::buf::byte::ByteBuf;

struct EventHandler;

impl Handler for EventHandler {
    type Timeout = ();
    type Message = ();

    fn ready(&mut self, event_loop: &mut EventLoop<EventHandler>, token: Token, events: EventSet) {
    }
}

pub struct Connection {
    sock: TcpStream,
    send_queue: Vec<ByteBuf>,
}

impl Connection {
    pub fn writable(&mut self, event_loop: &mut EventLoop<EventHandler>) -> Result<(), String> {
        while !self.send_queue.is_empty() {
            if !self.send_queue.first().unwrap().has_remaining() {
                self.send_queue.pop();
            }
            let buf = self.send_queue.first_mut().unwrap();
            match self.sock.try_write_buf(&mut buf) {
                Ok(None) => {
                    return Ok(());
                }
                Ok(Some(n)) => {
                    continue;
                }
                Err(e) => {
                    return Err(format!("{}", e));
                }
            }
        }
    Ok(())
    }
}

fn main() {
    println!("Hello, world!");
}

Cargo.toml包含以下依赖项:

mio = "*"
bytes = "*"

当前转换为Cargo.lock中的字节0.2.11和mio 0.4.3。

我得到的错误是:

main.rs:45:29: 45:52 error: the trait `bytes::buf::Buf` is not implemented
            for the type `&mut bytes::buf::byte::ByteBuf` [E0277]
main.rs:45             match self.sock.try_write_buf(&mut buf) {

我希望能够在套接字中写入Vec<u8>并在仅部分写入缓冲区时处理这种情况。我怎么能做到这一点?

我不需要解释有关正确处理返回值的代码,这个问题与缓冲区类型有关。我不知道我必须使用哪种缓冲区类型。

1 个答案:

答案 0 :(得分:2)

问题在于:

let buf = self.send_queue.first_mut().unwrap();
match self.sock.try_write_buf(&mut buf) {

您将&mut &mut ByteBuf传递给try_write_buf,因为buf已经是&mut ByteBuf。只需删除额外的&mut

let buf = self.send_queue.first_mut().unwrap();
match self.sock.try_write_buf(buf) {