Skip to main content

ClientBuilder

Struct ClientBuilder 

Source
pub struct ClientBuilder { /* private fields */ }
Expand description

Configures a Client. Defaults follow socket.io-client 4.8.

use std::time::Duration;
use socketio_next::{ClientBuilder, Event, Client};
use serde_json::json;

let client = ClientBuilder::new("http://localhost:4200")
    .namespace("/admin")
    .query("token", "s3cr3t")
    .auth(json!({ "user": "me" }))
    .on("chat", |event: Event, _client: Client| async move {
        println!("chat: {:?}", event.payload());
    })
    .connect()
    .await?;
client.emit("chat", "hello")?;
let reply = client.emit_with_ack("sum", vec![json!(1), json!(2)], Duration::from_secs(5)).await?;
client.disconnect().await?;

Implementations§

Source§

impl ClientBuilder

Source

pub fn new(address: impl Into<String>) -> Self

A builder for the server at address (http, https, ws or wss).

Like socket.io-client, the URL path is the namespace (http://host/admin joins /admin); the engine.io path is path (default /socket.io/).

Source

pub fn namespace(self, namespace: impl Into<String>) -> Self

The namespace to join (overrides the URL path). A missing leading / is added.

Source

pub fn path(self, path: impl Into<String>) -> Self

The engine.io path on the server (socket.io-client path, default /socket.io/).

Source

pub fn query(self, key: impl Into<String>, value: impl Into<String>) -> Self

Adds a query parameter to every request (socket.io-client query). Values are percent-encoded and, by default, shown as *** in logs (see redact_query).

Source

pub fn header(self, key: impl Into<String>, value: impl Into<String>) -> Self

Adds an HTTP header to every polling request and the websocket handshake (socket.io-client extraHeaders). Fails at connect() when it is not valid HTTP.

Source

pub fn auth(self, auth: impl Into<Value>) -> Self

The CONNECT payload (socket.io-client auth object), read by the server as socket.handshake.auth. Must be a JSON object (connect() fails with Error::InvalidAuth otherwise).

Source

pub fn auth_with<F, Fut>(self, auth: F) -> Self
where F: Fn() -> Fut + Send + Sync + 'static, Fut: Future<Output = Value> + Send + 'static,

Computes the CONNECT payload before every connect and reconnect (socket.io-client auth as a function), e.g. to refresh a token. Overrides auth.

Source

pub fn connect_params_with<F, Fut>(self, params: F) -> Self
where F: Fn() -> Fut + Send + Sync + 'static, Fut: Future<Output = ConnectParams> + Send + 'static,

Computes query parameters and headers before every connect and reconnect, e.g. a signed timestamp or a fresh bearer token in Authorization. Runs inside the attempt’s timeout; a panic fails the attempt. Values replace the builder’s ones of the same key.

Source

pub fn tls_config(self, tls_config: impl Into<TlsConfig>) -> Self

Available on crate features native-tls or rustls only.

TLS for https/wss: a TlsConfig, a rustls::ClientConfig or a native_tls::TlsConnector. Default: the backend’s default roots.

Source

pub fn proxy(self, proxy: impl Into<String>) -> Self

Sends polling requests and the websocket through the HTTP proxy proxy (http://[user:password@]host:port; the websocket goes through a CONNECT tunnel with basic auth from the user info). Without it the environment is used: HTTPS_PROXY / HTTP_PROXY / ALL_PROXY and NO_PROXY, for polling and websocket alike.

Source

pub fn no_proxy(self) -> Self

No proxy for any transport, whatever HTTPS_PROXY / HTTP_PROXY say (environment proxies apply to ws:// too; a proxy that refuses CONNECT to other ports than 443 would otherwise break websockets; with TransportType::Any the client then stays on polling after the failed upgrade).

Source

pub fn transport_type(self, transport: TransportType) -> Self

Which engine.io transports to use (default: polling, upgraded to websocket, polling when the websocket fails).

Source

pub fn timeout(self, timeout: Duration) -> Self

Bound for one connect attempt: engine.io handshake, upgrade and namespace CONNECT (socket.io-client timeout, default 20 s).

Source

pub fn reconnection(self, reconnection: bool) -> Self

Reconnect after a lost connection (socket.io-client reconnection, default on).

Source

pub fn reconnection_attempts(self, attempts: u32) -> Self

At most this many reconnect attempts per outage (socket.io-client reconnectionAttempts, default unlimited). Then the client closes with DisconnectReason::ReconnectFailed.

Source

pub fn reconnection_delay(self, delay: Duration) -> Self

First reconnect delay (socket.io-client reconnectionDelay, default 1 s). Attempt n waits delay * 2^(n-1), randomised, capped by reconnection_delay_max. The first attempt waits too.

Source

pub fn reconnection_delay_max(self, delay: Duration) -> Self

Longest reconnect delay (socket.io-client reconnectionDelayMax, default 5 s).

Source

pub fn randomization_factor(self, factor: f64) -> Self

Randomises each delay by up to ± this fraction (socket.io-client randomizationFactor, default 0.5; 0 disables).

Source

pub fn reconnect_on_disconnect(self, reconnect: bool) -> Self

Also reconnect after the server disconnected the socket (socket.io-client does not; default off).

Source

pub fn buffer_while_disconnected(self, buffer: bool) -> Self

Queue emits while disconnected and send them after the next connect, like socket.io-client’s sendBuffer (default off: emit fails fast with Error::NotConnected). Pending acks keep their timeout.

Source

pub fn redact_query(self, redact: bool) -> Self

Show query values as *** in logs and Debug output (default on; the engine.io parameters stay visible). Errors never contain the URL either way.

Source

pub fn inspect_packets<F>(self, inspector: F) -> Self
where F: Fn(Direction, &Packet) + Send + Sync + 'static,

Sees every socket.io packet in and out, after decoding / before encoding. For debugging; runs on the connection task, so keep it quick.

Source

pub fn on<M>( self, event: impl Into<String>, handler: impl Handler<Event, M>, ) -> Self

Handles event (see Handler for the closure forms).

Source

pub fn once<M>( self, event: impl Into<String>, handler: impl Handler<Event, M>, ) -> Self

Handles the next event only.

Source

pub fn on_any<M>(self, handler: impl Handler<Event, M>) -> Self

Handles every event (socket.io-client onAny), before the event’s own handlers.

Source

pub fn on_state_change<M>( self, handler: impl Handler<ConnectionState, M>, ) -> Self

Sees every ConnectionState transition, in order with the events.

Source

pub fn engine_url(&self) -> Result<Url>

The engine.io URL connect() will use (before connect_params_with): the address with its path replaced by path (the URL’s path is the namespace) and the query added, normalized the way the connection normalizes it (/v1/../x/ is /x/). For checking where a connection goes, e.g. against an allow-list.

Source

pub async fn connect(self) -> Result<Client>

Connects and joins the namespace. Resolves once the server answered CONNECT; fails with the error of this first attempt (no retry: reconnects start after a connection existed).

Trait Implementations§

Source§

impl Debug for ClientBuilder

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more