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
63
64
65
66
67
68
69
use simpletcp::simpletcp::{Error, Message, TcpServer};
fn main() {
let server = TcpServer::new("0.0.0.0:4328").unwrap();
let mut clients = Vec::new();
loop {
// Check for new clients
match server.accept().unwrap() {
None => {}
Some(client) => {
clients.push(Some(client));
}
}
// Handle clients
for client_opt in &mut clients {
let client = client_opt.as_mut().unwrap();
match client.read() {
Ok(msg) => match msg {
None => {}
Some(mut msg) => {
let a = msg.read_i32().unwrap();
let b = msg.read_i32().unwrap();
let r = a + b;
let mut response = Message::new();
response.write_i32(r);
client.write(&response).unwrap();
}
},
Err(err) => match err {
Error::NotReady => match client.get_ready() {
Ok(ready) => {
if ready {
println!("Client became ready!");
}
}
Err(_) => {
println!("Error while getting ready");
}
},
Error::EncryptionError(_) => {
println!("Error::EncryptionError");
}
Error::TcpError(_) => {
println!("Error::TcpError");
}
Error::ConnectionClosed => {
println!("Error::ConnectionClosed");
client_opt.take();
}
Error::SizeLimitExceeded => {
println!("Error::SizeLimitExceeded");
}
},
}
}
//Remove closed clients
clients.retain(|t| {
if t.is_none() {
println!("Removed client");
}
t.is_some()
});
}
}