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

A builder class for a socket.io socket. This handles setting up the client and configuring the callback, the namespace and metadata of the socket. If no namespace is specified, the default namespace / is taken. The connect method acts the build method and returns a connected Client.

Implementations

Create as client builder from a URL. URLs must be in the form [ws or wss or http or https]://[domain]:[port]/[path]. The path of the URL is optional and if no port is given, port 80 will be used.

Example
use socketio_rs::{Payload, ClientBuilder, Socket, AckId};
use serde_json::json;
use futures_util::future::FutureExt;


#[tokio::main]
async fn main() {
    let callback = |payload: Option<Payload>, socket: Socket, need_ack: Option<AckId>| {
        async move {
            match payload {
                Some(Payload::Json(data)) => println!("Received: {:?}", data),
                Some(Payload::Binary(bin)) => println!("Received bytes: {:#?}", bin),
                Some(Payload::Multi(multi)) => println!("Received multi: {:?}", multi),
                _ => {},
            }
        }.boxed()
    };

    let mut socket = ClientBuilder::new("http://localhost:4200")
        .namespace("/admin")
        .on("test", callback)
        .connect()
        .await
        .expect("error while connecting");

    // use the socket
    let json_payload = json!({"token": 123});

    let result = socket.emit("foo", json_payload).await;

    assert!(result.is_ok());
}

Sets the target namespace of the client. The namespace should start with a leading /. Valid examples are e.g. /admin, /foo. If the String provided doesn’t start with a leading /, it is added manually.

Registers a new callback for a certain crate::event::Event. The event could either be one of the common events like message, error, connect, close or a custom event defined by a string, e.g. onPayment or foo.

Example
use socketio_rs::{ClientBuilder, Payload};
use futures_util::FutureExt;

 #[tokio::main]
async fn main() {
    let socket = ClientBuilder::new("http://localhost:4200/")
        .namespace("/admin")
        .on("test", |payload: Option<Payload>, _, _| {
            async move {
                match payload {
                    Some(Payload::Json(data)) => println!("Received: {:?}", data),
                    Some(Payload::Binary(bin)) => println!("Received bytes: {:#?}", bin),
                    Some(Payload::Multi(multi)) => println!("Received multi: {:?}", multi),
                    _ => {},
                }
            }
            .boxed()
        })
        .on("error", |err, _, _| async move { eprintln!("Error: {:#?}", err) }.boxed())
        .connect()
        .await;
}
Issues with type inference for the callback method

Currently stable Rust does not contain types like AsyncFnMut. That is why this library uses the type FnMut(..) -> BoxFuture<_>, which basically represents a closure or function that returns a boxed future that can be executed in an async executor. The complicated constraints for the callback function bring the Rust compiler to it’s limits, resulting in confusing error messages when passing in a variable that holds a closure (to the on method). In order to make sure type inference goes well, the futures_util::FutureExt::boxed method can be used on an async block (the future) to make sure the return type is conform with the generic requirements. An example can be found here:

use socketio_rs::{ClientBuilder, Payload};
use futures_util::FutureExt;

#[tokio::main]
async fn main() {
    let callback = |payload: Option<Payload>, _, _| {
            async move {
                match payload {
                    Some(Payload::Json(data)) => println!("Received: {:?}", data),
                    Some(Payload::Binary(bin)) => println!("Received bytes: {:#?}", bin),
                    Some(Payload::Multi(multi)) => println!("Received multi: {:?}", multi),
                    _ => {},
                }
            }
            .boxed() // <-- this makes sure we end up with a `BoxFuture<_>`
        };

    let socket = ClientBuilder::new("http://localhost:4200/")
        .namespace("/admin")
        .on("test", callback)
        .connect()
        .await;
}

Sets custom http headers for the opening request. The headers will be passed to the underlying transport type (either websockets or polling) and then get passed with every request thats made. via the transport layer.

Example
use socketio_rs::{ClientBuilder, Payload};
use futures_util::future::FutureExt;

#[tokio::main]
async fn main() {
    let socket = ClientBuilder::new("http://localhost:4200/")
        .namespace("/admin")
        .on("error", |err, _, _| async move { eprintln!("Error: {:#?}", err) }.boxed())
        .opening_header("accept-encoding", "application/json")
        .connect()
        .await;
}

Specifies which EngineIO TransportType to use.

Example
use socketio_rs::{ClientBuilder, TransportType};

#[tokio::main]
async fn main() {
    let socket = ClientBuilder::new("http://localhost:4200/")
        // Use websockets to handshake and connect.
        .transport_type(TransportType::Websocket)
        .connect()
        .await
        .expect("connection failed");
}

Connects the socket to a certain endpoint. This returns a connected Client instance. This method returns an std::result::Result::Err value if something goes wrong during connection. Also starts a separate thread to start polling for packets. Used with callbacks.

Example
use socketio_rs::{ClientBuilder, Payload};
use serde_json::json;
use futures_util::future::FutureExt;

#[tokio::main]
async fn main() {
    let mut socket = ClientBuilder::new("http://localhost:4200/")
        .namespace("/admin")
        .on("error", |err, _, _| async move { eprintln!("Error: {:#?}", err) }.boxed())
        .connect()
        .await
        .expect("connection failed");

    // use the socket
    let json_payload = json!({"token": 123});

    let result = socket.emit("foo", json_payload).await;

    assert!(result.is_ok());
}

Trait Implementations

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

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

Calls U::from(self).

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

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more