Gelbpunkt / tokio-websockets

High performance, strict, tokio-util based websockets implementation
MIT License
57 stars 11 forks source link

tokio-websockets

Crates.io GitHub Workflow Status (with event) Documentation

High performance, strict, tokio-util based WebSockets implementation.

Why use tokio-websockets?

Feature flags

Feature flags in tokio-websockets are added to allow tailoring it to your needs.

TLS is supported via any of the following feature flags:

The rustls-*-roots and rustls-platform-verifier features require a crypto provider for rustls. You can either enable the aws_lc_rs (optionally also FIPS-compliant via the fips feature) or ring features to use these crates as the providers and then use TlsConnector::new(), or bring your own with TlsConnector::new_rustls_with_crypto_provider().

One SHA1 implementation is required, usually provided by the TLS implementation:

The client feature requires enabling one random number generator:

Example

This is a simple WebSocket echo server without any proper error handling.

More examples can be found in the examples folder.

use futures_util::{SinkExt, StreamExt};
use http::Uri;
use tokio::net::TcpListener;
use tokio_websockets::{ClientBuilder, Error, Message, ServerBuilder};

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

  tokio::spawn(async move {
    while let Ok((stream, _)) = listener.accept().await {
      let mut ws_stream = ServerBuilder::new()
        .accept(stream)
        .await?;

      tokio::spawn(async move {
        // Just an echo server, really
        while let Some(Ok(msg)) = ws_stream.next().await {
          if msg.is_text() || msg.is_binary() {
            ws_stream.send(msg).await?;
          }
        }

        Ok::<_, Error>(())
      });
    }

    Ok::<_, Error>(())
  });

  let uri = Uri::from_static("ws://127.0.0.1:3000");
  let (mut client, _) = ClientBuilder::from_uri(uri).connect().await?;

  client.send(Message::text("Hello world!")).await?;

  while let Some(Ok(msg)) = client.next().await {
    if let Some(text) = msg.as_text() {
      assert_eq!(text, "Hello world!");
      // We got one message, just stop now
      client.close().await?;
    }
  }

  Ok(())
}

MSRV

The current MSRV for all feature combinations is Rust 1.79.

Caveats / Limitations / ToDo

WebSocket compression is currently unsupported.