summaryrefslogtreecommitdiff
path: root/src/bin/server.rs
blob: ea961b78772f6222c9be8c01b06401cfa57ac34e (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
extern crate space;

use std::collections::HashMap;
use std::net::TcpListener;
use std::thread::sleep;
use std::time::Duration;

use space::mass::Mass;
use space::math::rand_name;
use space::server::connection::ServerConnection;

fn populate() -> HashMap<String, Mass> {
    let mut masses: HashMap<String, Mass> = HashMap::new();

    for _ in 0..10 {
        masses.insert(rand_name(), Mass::new_astroid());
    }

    masses
}

fn main() {
    let listener = TcpListener::bind("localhost:6000").unwrap();
    listener.set_nonblocking(true).unwrap();

    let mut masses = populate();

    let mut connections: Vec<ServerConnection> = Vec::new();
    for stream in listener.incoming() {
        match stream {
            Ok(stream) => {
                let new_connection = ServerConnection::new(stream, &mut masses);
                let exists = connections.iter().position(|connection| {
                    connection.name == new_connection.name
                        && connection.module_type == new_connection.module_type
                });
                if let Some(index) = exists {
                    connections.remove(index);
                }
                connections.push(new_connection);
            }
            _ => {
                for connection in &mut connections {
                    connection.process(&mut masses);
                }

                for mass in masses.values_mut() {
                    mass.process();
                }

                sleep(Duration::from_millis(100));
            }
        }
    }
}