Crate simple_websockets[][src]

An easy-to-use async WebSocket server using tokio.

To start a WebSocket listener, simply call launch(), and use the returned EventHub to react to client messages, connections, and disconnections.

Example

A WebSocket echo server:

use simple_websockets::{Event, Responder};
use std::collections::HashMap;

fn main() {
    // listen for WebSockets on port 8080:
    let event_hub = simple_websockets::launch(8080)
        .expect("failed to listen on port 8080");
    // map between client ids and the client's `Responder`:
    let mut clients: HashMap<u64, Responder> = HashMap::new();

    loop {
        let event = match event_hub.next_event() {
            Some(e) => e,
            None => continue,
        };

        match event {
            Event::Connect(client_id, responder) => {
                println!("A client connected with id #{}", client_id);
                // add their Responder to our `clients` map:
                clients.insert(client_id, responder);
            },
            Event::Disconnect(client_id) => {
                println!("Client #{} disconnected.", client_id);
                // remove the disconnected client from the clients map:
                clients.remove(&client_id);
            },
            Event::Message(client_id, message) => {
                println!("Received a message from client #{}: {:?}", client_id, message);
                // retrieve this client's `Responder`:
                let responder = clients.get(&client_id).unwrap();
                // echo the message back:
                responder.send(message);
            },
        }
    }
}

Structs

EventHub

A queue of incoming events from clients.

Responder

Sends outgoing messages to a websocket. Every connected websocket client has a corresponding Responder.

Enums

Error
Event

An incoming event from a client. This can be an incoming message, a new client connection, or a disconnection.

Message

An outgoing/incoming message to/from a websocket.

Functions

launch

Start listening for websocket connections on port. On success, returns an EventHub for receiving messages and connection/disconnection notifications.