-
-
Notifications
You must be signed in to change notification settings - Fork 56
/
salvo_echo.rs
55 lines (44 loc) · 1.59 KB
/
salvo_echo.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
53
54
55
use rmpv::Value;
use salvo::prelude::*;
use socketioxide::{
extract::{AckSender, Data, SocketRef},
SocketIo,
};
use tower::ServiceBuilder;
use tower_http::cors::CorsLayer;
use tracing::info;
use tracing_subscriber::FmtSubscriber;
fn on_connect(socket: SocketRef, Data(data): Data<Value>) {
info!(ns = socket.ns(), ?socket.id, "Socket.IO connected");
socket.emit("auth", &data).ok();
socket.on("message", |socket: SocketRef, Data::<Value>(data)| {
info!(?data, "Received event");
socket.emit("message-back", &data).ok();
});
socket.on("message-with-ack", |Data::<Value>(data), ack: AckSender| {
info!(?data, "Received event");
ack.send(&data).ok();
});
}
#[handler]
async fn hello() -> &'static str {
"Hello World"
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let subscriber = FmtSubscriber::new();
tracing::subscriber::set_global_default(subscriber)?;
let (layer, io) = SocketIo::new_layer();
// This code is used to integrates other tower layers before or after Socket.IO such as CORS
// Beware that classic salvo request won't pass through these layers
let layer = ServiceBuilder::new()
.layer(CorsLayer::permissive()) // Enable CORS policy
.layer(layer); // Mount Socket.IO
io.ns("/", on_connect);
io.ns("/custom", on_connect);
let layer = layer.compat();
let router = Router::with_path("/socket.io").hoop(layer).goal(hello);
let acceptor = TcpListener::new("127.0.0.1:3000").bind().await;
Server::new(acceptor).serve(router).await;
Ok(())
}