1use futures_util::StreamExt as _;
2use tipsy::{Endpoint, OnConflict, ServerId};
3use tokio::io::{AsyncReadExt, AsyncWriteExt, split};
4
5async fn run_server(path: String) {
6 let endpoint = Endpoint::new(ServerId::new(path), OnConflict::Overwrite).unwrap();
7
8 let incoming = endpoint.incoming().expect("failed to open new socket");
9 futures_util::pin_mut!(incoming);
10
11 while let Some(result) = incoming.next().await {
12 match result {
13 Ok(stream) => {
14 let (mut reader, mut writer) = split(stream);
15
16 tokio::spawn(async move {
17 loop {
18 let mut buf = [0u8; 4];
19
20 if reader.read_exact(&mut buf).await.is_err() {
21 println!("Closing socket");
22 break;
23 }
24 if let Ok("ping") = std::str::from_utf8(&buf[..]) {
25 println!("RECEIVED: PING");
26 writer
27 .write_all(b"pong")
28 .await
29 .expect("unable to write to socket");
30 println!("SEND: PONG");
31 }
32 }
33 });
34 }
35 _ => unreachable!("ideally"),
36 }
37 }
38}
39
40#[tokio::main]
41async fn main() {
42 let path = std::env::args()
43 .nth(1)
44 .expect("Run it with server path as argument");
45 run_server(path).await;
46}