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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
use core::fmt;
use std::fmt::Formatter;
use std::net::IpAddr;
use std::sync::Arc;
use std::time::Instant;
use custom_error::custom_error;
use log::{error, info, warn};
use tokio::io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::{mpsc, RwLock};
use tokio::sync::mpsc::{Receiver, Sender};
use tokio::task;
use crate::grid::{Grid, Size};
use crate::pixel::Pixel;
const PIXEL_BUFFER: usize = 1024;
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 ...";
custom_error! { ServerError
UnknownCommand = "Unknown command send!"
}
pub struct Server<G: Grid + std::marker::Send + std::marker::Sync> {
interface: IpAddr,
port: u16,
grid: Arc<RwLock<G>>,
}
impl<G> Server<G>
where
G: 'static + Grid + std::marker::Send + std::marker::Sync,
{
pub fn new(interface: IpAddr, port: u16, grid: G) -> Server<G> {
Server {
interface,
port,
grid: Arc::new(RwLock::new(grid)),
}
}
pub async fn start(self) -> Result<(), Box<dyn std::error::Error>> {
let listener = TcpListener::bind((self.interface, self.port)).await?;
let (tx, rx) = mpsc::channel(PIXEL_BUFFER);
let write_grid = Arc::clone(&self.grid);
task::spawn(async move {
draw_pixels(rx, write_grid).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);
let tx = tx.clone();
task::spawn(async move {
match process(&mut socket, grid, tx).await {
Ok(()) => info!("{} disconnects", addr),
Err(e) => warn!("{} disconnects because of: {}", addr, e),
}
});
}
Err(e) => error!("Error opening socket connection: {}", e),
};
}
}
}
async fn draw_pixels<G: Grid>(mut rx: Receiver<Pixel>, grid: Arc<RwLock<G>>) {
let buf: &mut Vec<Pixel> = &mut vec!();
let mut time = Instant::now();
loop {
if let Some(px) = rx.recv().await {
buf.push(px);
}
if !buf.is_empty() && (buf.len() > PIXEL_BUFFER || time.elapsed().as_micros() > 900) {
let mut grid = grid.write().await;
buf.iter().for_each(|px| grid.draw(px));
buf.clear();
time = Instant::now();
}
}
}
async fn process<G: Grid>(
socket: &mut TcpStream,
grid: Arc<RwLock<G>>,
tx: Sender<Pixel>,
) -> 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.read().await;
pixel = grid.fetch(line.parse()?);
}
if pixel.is_some() {
let pixel = format!("{}\n", pixel.unwrap());
wr.write(pixel.as_bytes()).await?;
}
}
3 => {
tx.send(line.parse()?).await?;
}
_ => return Err(Box::new(ServerError::UnknownCommand)),
}
}
Some("SIZE") => {
let size;
{
let grid = grid.read().await;
size = format!("{}\n", grid.size());
}
wr.write(size.as_bytes()).await?;
}
Some("HELP") => {
let help = format!("{}\n", 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 {
write!(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");
}
}