-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.rs
51 lines (43 loc) · 1.3 KB
/
main.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
mod codec;
use crate::codec::RespCodec;
use lazy_static::lazy_static;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Mutex;
use std::env;
use tokio::net::TcpListener;
use tokio::net::TcpStream;
use tokio::prelude::*;
use tokio_codec::Decoder;
mod commands;
use crate::commands::process_client_request;
lazy_static! {
static ref RUDIS_DB: Mutex<HashMap<String, String>> = Mutex::new(HashMap::new());
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let addr = env::args()
.skip(1)
.next()
.unwrap_or("127.0.0.1:6378".to_owned());
let addr = addr.parse::<SocketAddr>()?;
let listener = TcpListener::bind(&addr)?;
println!("rudis_async listening on: {}", addr);
let server_future = listener
.incoming()
.map_err(|e| println!("failed to accept socket; error = {:?}", e))
.for_each(handle_client);
tokio::run(server_future);
Ok(())
}
fn handle_client(client: TcpStream) -> Result<(), ()> {
let (tx, rx) = RespCodec.framed(client).split();
let reply = rx.and_then(process_client_request);
let task = tx.send_all(reply).then(|res| {
if let Err(e) = res {
eprintln!("failed to process connection; error = {:?}", e);
}
Ok(())
});
tokio::spawn(task);
Ok(())
}