routerify_websocket/
lib.rs

1//! The `WebSocket` support for the [Routerify](https://github.com/routerify/routerify) library.
2//!
3//! # Examples
4//!
5//! ```no_run
6//! // Import `SinkExt` and `StreamExt` to send and read websocket messages.
7//! use futures::{SinkExt, StreamExt};
8//! use hyper::{Body, Response, Server};
9//! use routerify::{Router, RouterService};
10//! // Import websocket types.
11//! use routerify_websocket::{upgrade_ws, Message, WebSocket};
12//! use std::{convert::Infallible, net::SocketAddr};
13//!
14//! // A handler for websocket connections.
15//! async fn ws_handler(ws: WebSocket) {
16//!     println!("New websocket connection: {}", ws.remote_addr());
17//!
18//!     // The `WebSocket` implements the `Sink` and `Stream` traits
19//!     // to read and write messages.
20//!     let (mut tx, mut rx) = ws.split();
21//!
22//!     // Read messages.
23//!     while let Some(msg) = rx.next().await {
24//!         let msg = msg.unwrap();
25//!
26//!         // Check message type and take appropriate actions.
27//!         if msg.is_text() {
28//!             println!("{}", msg.into_text().unwrap());
29//!         } else if msg.is_binary() {
30//!             println!("{:?}", msg.into_bytes());
31//!         }
32//!
33//!         // Send a text message.
34//!         let send_msg = Message::text("Hello world");
35//!         tx.send(send_msg).await.unwrap();
36//!     }
37//! }
38//!
39//! fn router() -> Router<Body, Infallible> {
40//!     // Create a router and specify the path and the handler for new websocket connections.
41//!     Router::builder()
42//!         // It will accept websocket connections at `/ws` path with any method type.
43//!         .any_method("/ws", upgrade_ws(ws_handler))
44//!         // It will accept http connections at `/` path.
45//!         .get("/", |_req| async move {
46//!             Ok(Response::new("I also serve http requests".into()))
47//!         })
48//!         .build()
49//!         .unwrap()
50//! }
51//!
52//! #[tokio::main]
53//! async fn main() {
54//!     let router = router();
55//!
56//!     // Create a Service from the router above to handle incoming requests.
57//!     let service = RouterService::new(router).unwrap();
58//!
59//!     // The address on which the server will be listening.
60//!     let addr = SocketAddr::from(([127, 0, 0, 1], 3001));
61//!
62//!     // Create a server by passing the created service to `.serve` method.
63//!     let server = Server::bind(&addr).serve(service);
64//!
65//!     println!("App is running on: {}", addr);
66//!     if let Err(err) = server.await {
67//!         eprintln!("Server error: {}", err);
68//!     }
69//! }
70//! ```
71
72pub use self::error::WebsocketError;
73pub use message::Message;
74pub use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, WebSocketConfig};
75pub use upgrade::{upgrade_ws, upgrade_ws_with_config};
76pub use websocket::WebSocket;
77
78mod error;
79mod message;
80mod upgrade;
81mod websocket;
82
83/// A Result type often returned while handing websocket connection.
84pub type Result<T> = std::result::Result<T, WebsocketError>;