Skip to main content

Crate socketeer

Crate socketeer 

Source
Expand description

§socketeer

Crates.io Version docs.rs GitHub branch status Codecov

socketeer is a simplified async WebSocket client built on tokio-tungstenite. It manages the underlying connection and exposes a clean API for sending and receiving messages, with support for:

  • Automatic connection management with configurable keepalive
  • Pluggable codec for typed messages (JsonCodec, MsgPackCodec, RawCodec, or your own)
  • Custom HTTP headers on the WebSocket upgrade request
  • Connection lifecycle hooks for auth handshakes and subscriptions
  • Transparent handling of WebSocket protocol messages (ping/pong/close)
  • Reconnection with automatic re-authentication

§Usage

§Simple JSON messages

use socketeer::{JsonCodec, Socketeer};

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct SocketMessage {
    message: String,
}

#[tokio::main]
async fn main() {
    let mut socketeer: Socketeer<JsonCodec<SocketMessage, SocketMessage>> =
        Socketeer::connect("ws://127.0.0.1:80")
            .await
            .unwrap();
    socketeer
        .send(SocketMessage {
            message: "Hello, world!".to_string(),
        })
        .await
        .unwrap();
    let response = socketeer.next_message().await.unwrap();
    println!("{response:#?}");
    socketeer.close_connection().await.unwrap();
}

§MessagePack

Enable the msgpack feature and use [MsgPackCodec] in place of JsonCodec:

use socketeer::{MsgPackCodec, Socketeer};

#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct SocketMessage { message: String }

let mut socketeer: Socketeer<MsgPackCodec<SocketMessage, SocketMessage>> =
    Socketeer::connect("ws://127.0.0.1:80").await.unwrap();

§Custom headers and connection options

use socketeer::{ConnectOptions, JsonCodec, Socketeer};
use std::time::Duration;

let mut options = ConnectOptions::default();
options.extra_headers.insert("Authorization", "Bearer my-token".parse().unwrap());
options.keepalive_interval = Some(Duration::from_secs(10));

let socketeer: Socketeer<JsonCodec<Msg, Msg>> =
    Socketeer::connect_with("wss://api.example.com/ws", options)
        .await
        .unwrap();

§Connection lifecycle hooks

use socketeer::{Codec, ConnectOptions, ConnectionHandler, Error, HandshakeContext, JsonCodec, Socketeer};

struct MyAuthHandler { api_key: String }

impl<C: Codec> ConnectionHandler<C> for MyAuthHandler {
    async fn on_connected(&mut self, ctx: &mut HandshakeContext<'_, C>) -> Result<(), Error> {
        ctx.send_text(&format!(r#"{{"action":"auth","key":"{}"}}"#, self.api_key)).await?;
        let _response = ctx.recv_text().await?;
        Ok(())
    }
}

let handler = MyAuthHandler { api_key: "secret".into() };
let socketeer: Socketeer<JsonCodec<Msg, Msg>, MyAuthHandler> =
    Socketeer::connect_with_codec(
        "wss://stream.example.com",
        ConnectOptions::default(),
        JsonCodec::new(),
        handler,
    )
    .await
    .unwrap();
// Handler's on_connected runs again automatically on reconnect

Structs§

ConnectOptions
Configuration options for a WebSocket connection.
HandshakeContext
Context available during the WebSocket handshake phase.
JsonCodec
JSON codec backed by serde_json.
NoopHandler
Default no-op connection handler.
RawCodec
Identity codec — Tx and Rx are both Message, no (de)serialization.
Socketeer
A WebSocket client that manages the connection to a WebSocket server. The client can send and receive messages, and will transparently handle protocol messages.

Enums§

Error
Error type for the Socketeer library. This type is used to represent all possible external errors that can occur when using the Socketeer library.

Traits§

Codec
Encodes outgoing values into WebSocket messages and decodes incoming messages into typed values.
ConnectionHandler
Trait for handling WebSocket connection lifecycle events.