summaryrefslogtreecommitdiff
path: root/src/server_connection.rs
blob: 407b842dd488d174846a20b70a2d02ab4536ac64 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
extern crate serde_json;

use std::collections::HashMap;
use std::io::prelude::*;
use std::io::BufReader;
use std::net::TcpStream;

use crate::mass::Mass;
use crate::modules::types::ModuleType;

pub struct ServerConnection {
    pub name: String,
    pub module_type: ModuleType,
    pub stream: TcpStream,
    pub buff_r: BufReader<TcpStream>,
    pub open: bool,
}

impl ServerConnection {
    pub fn new(mut stream: TcpStream, masses: &mut HashMap<String, Mass>) -> ServerConnection {
        let mut buff_r = BufReader::new(stream.try_clone().unwrap());

        let mut recv = String::new();
        buff_r.read_line(&mut recv).unwrap();
        let name = &recv[..recv.find(':').unwrap()];

        let ship = masses
            .entry(name.to_string())
            .or_insert_with(Mass::new_ship);

        let send = serde_json::to_string(&ship.get_modules()).unwrap() + "\n";
        stream.write_all(send.as_bytes()).unwrap();

        let mut recv = String::new();
        buff_r.read_line(&mut recv).unwrap();
        let module_type: ModuleType = serde_json::from_str(&recv.replace("\n", "")).unwrap();

        stream.set_nonblocking(true).unwrap();
        ServerConnection {
            name: String::from(name),
            module_type,
            stream,
            buff_r,
            open: true,
        }
    }

    pub fn receive(&mut self) -> String {
        let mut recv = String::new();
        match self.buff_r.read_line(&mut recv) {
            Ok(result) => {
                if result == 0 {
                    self.open = false;
                    String::new()
                } else {
                    recv.replace("\n", "")
                }
            }
            Err(_) => String::new(),
        }
    }
}