humphrey_ws 0.2.0

WebSocket support for the Humphrey web server.
Documentation

WebSocket support for Humphrey.

The core Humphrey crate does not support WebSocket connections, but through its WebsocketHandler trait, it can be extended to support them, which is what this crate does.

Features

  • Performs WebSocket handshake and implements WebSocket according to RFC 6455.
  • Well-integrated with the core Humphrey crate
  • Supports WebSocket Secure connections using the TLS feature of the core Humphrey crate
  • Has no dependencies in accordance with Humphrey's goals of being dependency-free. This means SHA-1 (RFC 3174) and base64 (RFC 4648) are both implemented from scratch in this crate as they are required for the handshake.
  • Supports both blocking and non-blocking reads.

Installation

The Humphrey WebSocket crate can be installed by adding humphrey_ws to your dependencies in your Cargo.toml file.

Documentation

The Humphrey WebSocket documentation can be found at docs.rs.

Basic Example

use humphrey::App;
use humphrey::stream::Stream;

use humphrey_ws::error::WebsocketError;
use humphrey_ws::message::Message;
use humphrey_ws::stream::WebsocketStream;
use humphrey_ws::websocket_handler;

use std::sync::Arc;

fn main() {
    let app: App<()> = App::new()
        .with_websocket_route("/", websocket_handler(my_handler));
    app.run("0.0.0.0:80").unwrap();
}

fn my_handler(mut stream: WebsocketStream<Stream>, _: Arc<()>) {
    let hello_world = Message::new("Hello, World!");
    stream.send(hello_world).unwrap();

    loop {
        match stream.recv() {
            Ok(msg) => println!("Message: {}", msg.text().unwrap()),
            Err(WebsocketError::ConnectionClosed) => {
                break;
            },
            _ => ()
        }
    }

    println!("Connection closed");
}

Further Examples

  • Echo Server: echoes received messages back to the client with an incrementing number at the end
  • Broadcast: broadcasts messages to all connected clients using non-blocking reads