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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
use repl;
use std::io::{BufRead, Write};
use std::io::{BufReader, BufWriter};
use std::net::TcpStream;
use std::thread;
use vm::VM;
pub struct Client {
reader: BufReader<TcpStream>,
writer: BufWriter<TcpStream>,
raw_stream: TcpStream,
repl: repl::REPL,
}
impl Client {
pub fn new(stream: TcpStream) -> Client {
let reader = stream.try_clone().unwrap();
let writer = stream.try_clone().unwrap();
let vm = VM::new();
let repl = repl::REPL::new(vm);
Client {
reader: BufReader::new(reader),
writer: BufWriter::new(writer),
raw_stream: stream,
repl,
}
}
fn w(&mut self, msg: &str) -> bool {
match self.writer.write_all(msg.as_bytes()) {
Ok(_) => match self.writer.flush() {
Ok(_) => true,
Err(e) => {
println!("Error flushing to client: {}", e);
false
}
},
Err(e) => {
println!("Error writing to client: {}", e);
false
}
}
}
fn recv_loop(&mut self) {
let rx = self.repl.rx_pipe.take();
let mut writer = self.raw_stream.try_clone().unwrap();
let _t = thread::spawn(move || {
let chan = rx.unwrap();
loop {
match chan.recv() {
Ok(msg) => {
match writer.write_all(msg.as_bytes()) {
Ok(_) => {}
Err(_e) => {}
};
match writer.flush() {
Ok(_) => {}
Err(_e) => {}
}
}
Err(_e) => {}
}
}
});
}
pub fn run(&mut self) {
self.recv_loop();
let mut buf = String::new();
let banner = repl::REMOTE_BANNER.to_owned() + "\n" + repl::PROMPT;
self.w(&banner);
loop {
match self.reader.read_line(&mut buf) {
Ok(_) => {
buf.trim_right();
self.repl.run_single(&buf);
}
Err(e) => {
println!("Error receiving: {:#?}", e);
}
}
}
}
}