7 releases

0.1.6 Jun 14, 2023
0.1.5 Feb 7, 2023
0.1.4 Nov 9, 2021
0.1.3 Oct 26, 2021
0.1.1 Mar 11, 2021

#146 in WebSocket

Download history 37/week @ 2024-07-21 68/week @ 2024-07-28 59/week @ 2024-08-04 70/week @ 2024-08-11 41/week @ 2024-08-18 34/week @ 2024-08-25 29/week @ 2024-09-01 44/week @ 2024-09-08 26/week @ 2024-09-15 28/week @ 2024-09-22 87/week @ 2024-09-29 78/week @ 2024-10-06 64/week @ 2024-10-13 155/week @ 2024-10-20 156/week @ 2024-10-27 162/week @ 2024-11-03

545 downloads per month
Used in 2 crates

MIT license

15KB
176 lines

simple-websockets

An easy-to-use WebSocket server.

MIT licensed Docs Crates.io

Example

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 {
        match event_hub.poll_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);
            },
        }
    }
}

Dependencies

~4–10MB
~108K SLoC