-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathecho_server.rs
52 lines (44 loc) · 1.23 KB
/
echo_server.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
52
use structopt::StructOpt;
use tokio;
use tokio::spawn;
use yarws::{log, Error, Server, Socket};
#[macro_use]
extern crate slog;
#[derive(StructOpt, Debug)]
struct Args {
#[structopt(short = "p", long = "port", default_value = "9001")]
port: usize,
#[structopt(short = "i", long = "bind-ip", default_value = "127.0.0.1")]
ip: String,
}
impl Args {
fn addr(&self) -> String {
format!("{}:{}", self.ip, self.port)
}
}
#[tokio::main]
async fn main() -> Result<(), Error> {
let args = Args::from_args();
let log = log::config();
// bind to tcp port
let mut srv = Server::new(&args.addr()).logger(log.clone()).bind().await?;
// wait for incoming connection
while let Some(socket) = srv.accept().await {
let log = log.new(o!("conn" => socket.no));
// spawn task for handling socket
spawn(async move {
if let Err(e) = echo(socket).await {
error!(log, "{}", e);
}
});
}
Ok(())
}
async fn echo(mut socket: Socket) -> Result<(), Error> {
// read messages until connection is closed
while let Some(msg) = socket.recv().await {
// reply with the same message
socket.send(msg).await?;
}
Ok(())
}