2021-06-12 20:50:30 +02:00
|
|
|
//! Example websocket server.
|
|
|
|
//!
|
|
|
|
//! Run with
|
|
|
|
//!
|
|
|
|
//! ```
|
|
|
|
//! RUST_LOG=tower_http=debug,key_value_store=trace \
|
|
|
|
//! cargo run \
|
2021-07-30 15:19:53 +02:00
|
|
|
//! --all-features \
|
2021-06-12 20:50:30 +02:00
|
|
|
//! --example websocket
|
|
|
|
//! ```
|
|
|
|
|
2021-07-09 21:36:14 +02:00
|
|
|
use axum::{
|
2021-07-30 15:19:53 +02:00
|
|
|
extract::TypedHeader,
|
2021-06-13 11:22:02 +02:00
|
|
|
prelude::*,
|
|
|
|
routing::nest,
|
|
|
|
service::ServiceExt,
|
|
|
|
ws::{ws, Message, WebSocket},
|
|
|
|
};
|
2021-06-12 20:50:30 +02:00
|
|
|
use http::StatusCode;
|
|
|
|
use std::net::SocketAddr;
|
|
|
|
use tower_http::{
|
|
|
|
services::ServeDir,
|
|
|
|
trace::{DefaultMakeSpan, TraceLayer},
|
|
|
|
};
|
|
|
|
|
|
|
|
#[tokio::main]
|
|
|
|
async fn main() {
|
|
|
|
tracing_subscriber::fmt::init();
|
|
|
|
|
|
|
|
// build our application with some routes
|
|
|
|
let app = nest(
|
|
|
|
"/",
|
2021-07-09 21:36:14 +02:00
|
|
|
axum::service::get(
|
2021-06-13 00:17:17 +02:00
|
|
|
ServeDir::new("examples/websocket")
|
|
|
|
.append_index_html_on_directories(true)
|
|
|
|
.handle_error(|error: std::io::Error| {
|
2021-07-22 15:00:33 +02:00
|
|
|
Ok::<_, std::convert::Infallible>((
|
2021-06-13 00:17:17 +02:00
|
|
|
StatusCode::INTERNAL_SERVER_ERROR,
|
|
|
|
format!("Unhandled interal error: {}", error),
|
2021-07-22 15:00:33 +02:00
|
|
|
))
|
2021-06-13 00:17:17 +02:00
|
|
|
}),
|
|
|
|
),
|
2021-06-12 20:50:30 +02:00
|
|
|
)
|
|
|
|
// routes are matched from bottom to top, so we have to put `nest` at the
|
|
|
|
// top since it matches all routes
|
|
|
|
.route("/ws", ws(handle_socket))
|
|
|
|
// logging so we can see whats going on
|
|
|
|
.layer(
|
|
|
|
TraceLayer::new_for_http().make_span_with(DefaultMakeSpan::default().include_headers(true)),
|
|
|
|
);
|
|
|
|
|
|
|
|
// run it with hyper
|
|
|
|
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
|
|
|
|
tracing::debug!("listening on {}", addr);
|
2021-06-19 12:50:33 +02:00
|
|
|
hyper::Server::bind(&addr)
|
|
|
|
.serve(app.into_make_service())
|
|
|
|
.await
|
|
|
|
.unwrap();
|
2021-06-12 20:50:30 +02:00
|
|
|
}
|
|
|
|
|
2021-07-30 15:19:53 +02:00
|
|
|
async fn handle_socket(
|
|
|
|
mut socket: WebSocket,
|
|
|
|
// websocket handlers can also use extractors
|
|
|
|
TypedHeader(user_agent): TypedHeader<headers::UserAgent>,
|
|
|
|
) {
|
|
|
|
println!("`{}` connected", user_agent.as_str());
|
|
|
|
|
2021-06-12 20:50:30 +02:00
|
|
|
if let Some(msg) = socket.recv().await {
|
|
|
|
let msg = msg.unwrap();
|
|
|
|
println!("Client says: {:?}", msg);
|
|
|
|
}
|
|
|
|
|
|
|
|
loop {
|
|
|
|
socket.send(Message::text("Hi!")).await.unwrap();
|
|
|
|
tokio::time::sleep(std::time::Duration::from_secs(3)).await;
|
|
|
|
}
|
|
|
|
}
|