gameServer2/src/server/client.rs
author unc0rr
Wed, 25 Jan 2017 23:48:23 +0300
changeset 12144 589a2d7d3dc5
parent 12143 7e874846afe3
child 12146 8d8fb85bc09c
permissions -rw-r--r--
More refactoring

use mio::tcp::*;
use mio::*;
use std::io::Write;
use std::io;
use netbuf;

use utils;
use protocol::ProtocolDecoder;
use protocol::messages::*;
use super::actions::Action::*;
use super::actions::Action;

pub struct HWClient {
    sock: TcpStream,
    decoder: ProtocolDecoder,
    buf_out: netbuf::Buf,
    room_id: Token,

    pub nick: String,
    pub protocolNumber: u32,
}

impl HWClient {
    pub fn new(sock: TcpStream, roomId: &Token) -> HWClient {
        HWClient {
            sock: sock,
            decoder: ProtocolDecoder::new(),
            buf_out: netbuf::Buf::new(),
            room_id: roomId.clone(),

            nick: String::new(),
            protocolNumber: 0,
        }
    }

    pub fn register(&mut self, poll: &Poll, token: Token) {
        poll.register(&self.sock, token, Ready::all(),
                      PollOpt::edge())
            .ok().expect("could not register socket with event loop");

        self.send_msg(HWServerMessage::Connected(utils::PROTOCOL_VERSION));
    }

    pub fn deregister(&mut self, poll: &Poll) {
        poll.deregister(&self.sock);
    }

    pub fn send_raw_msg(&mut self, msg: &[u8]) {
        self.buf_out.write(msg).unwrap();
        self.flush();
    }

    pub fn send_string(&mut self, msg: &String) {
        self.send_raw_msg(&msg.as_bytes());
    }

    pub fn send_msg(&mut self, msg: HWServerMessage) {
        self.send_string(&msg.to_raw_protocol());
    }

    fn flush(&mut self) {
        self.buf_out.write_to(&mut self.sock).unwrap();
        self.sock.flush();
    }

    pub fn readable(&mut self, poll: &Poll) -> Vec<Action> {
        let v = self.decoder.read_from(&mut self.sock).unwrap();
        debug!("Read {} bytes", v);
        let mut response = Vec::new();
        {
            for msg in self.decoder.extract_messages() {
                response.push(ReactProtocolMessage(msg));
            }
        }
        self.decoder.sweep();
        response
    }

    pub fn writable(&mut self, poll: &Poll) -> io::Result<()> {
        self.buf_out.write_to(&mut self.sock)?;

        Ok(())
    }

    pub fn error(&mut self, poll: &Poll) -> Vec<Action> {
        return vec![ByeClient("Connection reset".to_string())]
    }
}