mio中缓冲区类型的问题



我想在Rust中使用mio编写一个异步服务器,我在缓冲区类型方面遇到了麻烦。我试过不同的缓冲类型,不能让它工作。我现在的代码是:

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>写入套接字并处理缓冲区仅部分写入的情况。我怎么才能做到呢?

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

问题是:

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) {

相关内容

  • 没有找到相关文章

最新更新