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 options = ConnectOptions::builder()
    .header("Authorization", "Bearer my-token".parse().unwrap())
    .keepalive_interval(Some(Duration::from_secs(10)))
    .build();

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

Re-exports§

pub use tokio_tungstenite::tungstenite;
pub use tokio_tungstenite::tungstenite::http;

Structs§

Bytes
A cheaply cloneable and sliceable chunk of contiguous memory.
ConnectOptions
Configuration options for a WebSocket connection.
ConnectOptionsBuilder
Builder for ConnectOptions. Obtain one with ConnectOptions::builder, chain setters, and finish with ConnectOptionsBuilder::build.
HandshakeContext
Context available during the WebSocket handshake phase.
JsonCodec
JSON codec backed by serde_json.
MsgPackCodec
MessagePack codec backed by rmp-serde.
NoopHandler
Default no-op connection handler.
RawCodec
Identity codec — Tx and Rx are both Message, no (de)serialization.
ReuniteError
Error returned by SocketeerRx::reunite when the two halves did not come from the same Socketeer::split. Carries both halves back so the caller can recover them.
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.
SocketeerRx
The receive half of a Socketeer, produced by Socketeer::split. Implements Stream and can be recombined with a SocketeerTx via reunite.
SocketeerTx
The cloneable send half of a Socketeer, produced by Socketeer::split. Clone it to send from multiple tasks concurrently.

Enums§

EchoControlMessage
Control messages for testing with the echo server.
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.
Message
An enum representing the various forms of a WebSocket message.

Traits§

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

Functions§

auth_echo_server
Echo server that requires an auth handshake before echoing.
echo_server
Basic echo server that sends back messages it receives. It will also respond to pings and close the connection upon request.
get_mock_address
Create a WebSocket server that handles a customizable set of requests and exits. If the spawned socket handler returns true, the server will exit.
msgpack_echo_server
MessagePack-flavored echo server.

Type Aliases§

WebSocketStreamType
The concrete WebSocketStream type the mock-server handlers operate on. Re-exported so downstream code can write custom servers for get_mock_address. Primarily useful with the mocking feature, which gates get_mock_address and the built-in test servers. The concrete WebSocketStream type the mock-server handlers operate on. Re-exported so downstream code can write custom servers for get_mock_address.