-
Notifications
You must be signed in to change notification settings - Fork 9
/
socket.rs
51 lines (44 loc) · 1.51 KB
/
socket.rs
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
extern crate shrust;
use shrust::{Shell, ShellIO};
use std::io::prelude::*;
use std::sync::{Arc, Mutex};
use std::thread;
use std::collections::HashMap;
use std::str::FromStr;
use std::net::TcpListener;
fn main() {
let map = Arc::new(Mutex::new(HashMap::new()));
let mut shell = Shell::new(map);
shell.new_command(&"put", &"Insert a value", 2, |_, map, args| {
map.lock().unwrap().insert(usize::from_str(args[0])?, args[1].to_string());
Ok(())
});
shell.new_command("get", "Get a value", 1, |io, map, args| {
match map.lock().unwrap().get(&usize::from_str(args[0])?) {
Some(val) => writeln!(io, "{}", val).unwrap(),
None => writeln!(io, "Not found").unwrap()
};
Ok(())
});
shell.new_command("remove", "Remove a value", 1, |_, map, args| {
map.lock().unwrap().remove(&usize::from_str(args[0])?);
Ok(())
});
shell.new_command("list", "List all values", 0, |io, map, _| {
for (k, v) in &*map.lock().unwrap() {
writeln!(io, "{} = {}", k, v).unwrap();
}
Ok(())
});
shell.new_command_noargs("clear", "Clear all values", |_, map| {
map.lock().unwrap().clear();
Ok(())
});
let serv = TcpListener::bind("0.0.0.0:1234").expect("Cannot open socket");
for sock in serv.incoming() {
let sock = sock.unwrap();
let mut shell = shell.clone();
let mut io = ShellIO::new_io(sock);
thread::spawn(move || shell.run_loop(&mut io));
}
}