#net #opcode #github #http #text #com-euvoor-hawk

nightly websocket-rs

Designed for https://github.com/euvoor/hawk

5 releases

0.1.4 Jun 17, 2020
0.1.3 Jun 17, 2020
0.1.2 Jun 17, 2020
0.1.1 Jun 17, 2020
0.1.0 Jun 8, 2020

#236 in WebSocket

MIT license

22KB
343 lines

Designed for HAWK

Example

use tokio::net::TcpListener;

use http_rs::Http;
use websocket_rs::{ Websocket, Opcode };

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut listener = TcpListener::bind("127.0.0.1:8080").await?;

    println!("Listening for websocket connections on 127.0.0.1:8080");

    while let Ok((stream, addr)) = listener.accept().await {
        tokio::spawn(async move {
            println!("New connection from {:?}", addr);

            let mut http = Http::new(stream);

            if let Some(req) = http.next().await {
                if req.for_websocket() {
                    let mut ws = Websocket::new_with_key(
                        http.transport.into_inner(),
                        req.headers.get("sec-websocket-key").unwrap().to_string()
                    );

                    while let Some(msg) = ws.next().await {
                        println!("{:?}", msg);

                        if msg.opcode == Opcode::Text {
                            let response = format!("Received: {:?}", msg.payload);
                            ws.send_text(response).await.unwrap();
                        }
                    }

                    println!("Client from {:?} disconnected", addr);
                }
            }
        });
    }

    Ok(())
}

TODO

  • Handle errors properly
  • Receive opcode TEXT
  • Pong when Ping is received
  • Handle all payload lengths (le 125, =126, =127)
  • Mask key
  • Close websocket connection
  • Read fragmented frames
  • Extract websocket to its own crate
  • Add binary support
  • Send fragmented frames when the size reaches a treshold
  • Schedule ping/pong
  • Pong with application data included in ping
  • Keep track of connected clients

Dependencies

~7–14MB
~130K SLoC