0

我想使用结构实现 TCP 客户端:

use std::error::Error;

use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
use std::io::Read;

const CLIENT: Token = Token(0);

pub struct Client {
    pub connected: bool,
    connection: Option<TcpStream>,
}

impl Client {
    pub fn connect(&mut self, host: &str, port: i16) {
        let addr = format!("{}:{}", host, port).parse().unwrap();

        if let Ok(stream) = TcpStream::connect(addr) {
            self.connected = true;
            self.connection = Some(stream);
        } else {
            println!("Cannot connect !");
        }
    }

    pub fn listen(&mut self) {
        let mut connection = self.connection.unwrap();
        let mut poll = Poll::new().unwrap();
        let mut events = Events::with_capacity(256);

        poll.registry().register(
            &mut connection,
            CLIENT,
            Interest::READABLE | Interest::WRITABLE
        );

        loop {
            // ...
        }
    }

    pub fn new() -> Client {
        Client {
            connected: false,
            connection: None,
        }
    }
}

但我得到一个错误:

let mut connection = self.connection.unwrap();
                     ^^^^^^^^^^^^^^^ move occurs because `self.connection` has type `Option<mio::net::TcpStream>`, which does not implement the `Copy` trait

我怎样才能解决这个问题 ?

4

0 回答 0