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 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
//! The `WebSocket` support for the [Routerify](https://github.com/routerify/routerify) library.
//!
//! # Examples
//!
//! ```no_run
//! // Import `SinkExt` and `StreamExt` to send and read websocket messages.
//! use futures::{SinkExt, StreamExt};
//! use hyper::{Body, Response, Server};
//! use routerify::{Router, RouterService};
//! // Import websocket types.
//! use routerify_websocket::{upgrade_ws, Message, WebSocket};
//! use std::{convert::Infallible, net::SocketAddr};
//!
//! // A handler for websocket connections.
//! async fn ws_handler(ws: WebSocket) {
//! println!("New websocket connection: {}", ws.remote_addr());
//!
//! // The `WebSocket` implements the `Sink` and `Stream` traits
//! // to read and write messages.
//! let (mut tx, mut rx) = ws.split();
//!
//! // Read messages.
//! while let Some(msg) = rx.next().await {
//! let msg = msg.unwrap();
//!
//! // Check message type and take appropriate actions.
//! if msg.is_text() {
//! println!("{}", msg.into_text().unwrap());
//! } else if msg.is_binary() {
//! println!("{:?}", msg.into_bytes());
//! }
//!
//! // Send a text message.
//! let send_msg = Message::text("Hello world");
//! tx.send(send_msg).await.unwrap();
//! }
//! }
//!
//! fn router() -> Router<Body, Infallible> {
//! // Create a router and specify the path and the handler for new websocket connections.
//! Router::builder()
//! // It will accept websocket connections at `/ws` path with any method type.
//! .any_method("/ws", upgrade_ws(ws_handler))
//! // It will accept http connections at `/` path.
//! .get("/", |_req| async move {
//! Ok(Response::new("I also serve http requests".into()))
//! })
//! .build()
//! .unwrap()
//! }
//!
//! #[tokio::main]
//! async fn main() {
//! let router = router();
//!
//! // Create a Service from the router above to handle incoming requests.
//! let service = RouterService::new(router).unwrap();
//!
//! // The address on which the server will be listening.
//! let addr = SocketAddr::from(([127, 0, 0, 1], 3001));
//!
//! // Create a server by passing the created service to `.serve` method.
//! let server = Server::bind(&addr).serve(service);
//!
//! println!("App is running on: {}", addr);
//! if let Err(err) = server.await {
//! eprintln!("Server error: {}", err);
//! }
//! }
//! ```
pub use self::error::WebsocketError;
pub use message::Message;
pub use tokio_tungstenite::tungstenite::protocol::{frame::coding::CloseCode, WebSocketConfig};
pub use upgrade::{upgrade_ws, upgrade_ws_with_config};
pub use websocket::WebSocket;
mod error;
mod message;
mod upgrade;
mod websocket;
/// A Result type often returned while handing websocket connection.
pub type Result<T> = std::result::Result<T, WebsocketError>;