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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use core::fmt;
use std::fmt::Formatter;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use custom_error::custom_error;
use log::{error, info, warn};
use tokio::io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::task;
use crate::grid::{Grid, Size};
use crate::pixel::Pixel;
const HELP: &str = "\
HELP Pixelflut Commands:\n\
HELP - PX <x> <y> <RRGGBB[AA]>\n\
HELP - PX <x> <y> >> PX <x> <y> <RRGGBB>\n\
HELP - SIZE >> SIZE <width> <height>\n\
HELP - HELP >> HELP ...\n";
custom_error! { ServerError
UnknownCommand = "Unknown command send!"
}
pub struct Server<G: Grid + std::marker::Send> {
interface: IpAddr,
port: u16,
grid: Arc<Mutex<G>>,
}
impl<G> Server<G>
where
G: 'static + Grid + std::marker::Send,
{
pub fn new(interface: IpAddr, port: u16, grid: G) -> Server<G> {
Server {
interface,
port,
grid: Arc::new(Mutex::new(grid)),
}
}
pub async fn start(self) -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind((self.interface, self.port)).await?;
info!("Server is ready and listening to {}:{}", self.interface, self.port);
loop {
match listener.accept().await {
Ok((mut socket, addr)) => {
info!("New connection from {}", addr);
let grid = Arc::clone(&self.grid);
task::spawn(async move {
match process(&mut socket, grid).await {
Ok(()) => info!("{} disconnects", addr),
Err(e) => warn!("{} disconnects because of: {}", addr, e),
}
});
}
Err(e) => error!("Error opening socket connection: {}", e),
};
}
}
}
async fn process<G: Grid>(
socket: &mut TcpStream,
grid: Arc<Mutex<G>>,
) -> Result<(), Box<dyn std::error::Error>> {
let (rd, mut wr) = io::split(socket);
let reader = BufReader::new(rd);
let mut lines = reader.lines();
while let Some(line) = lines.next_line().await? {
let mut parts = line.split_whitespace();
match parts.next() {
Some("PX") => {
match parts.count() {
2 => {
let pixel: Option<Pixel>;
{
let grid = grid.lock().unwrap();
pixel = grid.fetch(line.parse()?);
}
if pixel.is_some() {
wr.write(pixel.unwrap().to_string().as_bytes()).await?;
}
}
3 => {
let mut grid = grid.lock().unwrap();
grid.draw(line.parse()?)
}
_ => return Err(Box::new(ServerError::UnknownCommand)),
}
}
Some("SIZE") => {
let size;
{
let grid = grid.lock().unwrap();
size = grid.size().to_string();
}
wr.write(size.as_bytes()).await?;
}
Some("HELP") => { wr.write(HELP.as_bytes()).await?; }
_ => return Err(Box::new(ServerError::UnknownCommand)),
}
}
Ok(())
}
impl fmt::Display for Size {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
writeln!(f, "SIZE {} {}", self.x(), self.y())
}
}
#[cfg(test)]
mod tests {
use crate::grid::Size;
#[test]
fn display_size() {
let size = Size::new(1024, 768);
assert_eq!(size.to_string(), "SIZE 1024 768\n");
}
}