Expand description
§socketeer
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 reconnectRe-exports§
pub use tokio_tungstenite::tungstenite;pub use tokio_tungstenite::tungstenite::http;
Structs§
- Bytes
- A cheaply cloneable and sliceable chunk of contiguous memory.
- Connect
Options - Configuration options for a WebSocket connection.
- Connect
Options Builder - Builder for
ConnectOptions. Obtain one withConnectOptions::builder, chain setters, and finish withConnectOptionsBuilder::build. - Handshake
Context - Context available during the WebSocket handshake phase.
- Json
Codec - JSON codec backed by
serde_json. - MsgPack
Codec MessagePackcodec backed byrmp-serde.- Noop
Handler - Default no-op connection handler.
- RawCodec
- Identity codec —
TxandRxare bothMessage, no (de)serialization. - Reunite
Error - Error returned by
SocketeerRx::reunitewhen the two halves did not come from the sameSocketeer::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.
- Socketeer
Rx - The receive half of a
Socketeer, produced bySocketeer::split. ImplementsStreamand can be recombined with aSocketeerTxviareunite. - Socketeer
Tx - The cloneable send half of a
Socketeer, produced bySocketeer::split. Clone it to send from multiple tasks concurrently.
Enums§
- Echo
Control Message - 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.
- Connection
Handler - 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§
- WebSocket
Stream Type - The concrete
WebSocketStreamtype the mock-server handlers operate on. Re-exported so downstream code can write custom servers forget_mock_address. Primarily useful with themockingfeature, which gatesget_mock_addressand the built-in test servers. The concreteWebSocketStreamtype the mock-server handlers operate on. Re-exported so downstream code can write custom servers forget_mock_address.