Struct rust_socketio::asynchronous::ClientBuilder

source ·
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§

source§

impl ClientBuilder

source

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

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 rust_socketio::{Payload, asynchronous::{ClientBuilder, Client}};
use serde_json::json;
use futures_util::future::FutureExt;


#[tokio::main]
async fn main() {
    let callback = |payload: Payload, socket: Client| {
        async move {
            match payload {
                Payload::Text(values) => println!("Received: {:#?}", values),
                Payload::Binary(bin_data) => println!("Received bytes: {:#?}", bin_data),
                // This is deprecated, use Payload::Text instead
                Payload::String(str) => println!("Received: {}", str),
            }
        }.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());
}
source

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

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.

source

pub fn on<T: Into<Event>, F>(self, event: T, callback: F) -> Self
where F: for<'a> FnMut(Payload, Client) -> BoxFuture<'static, ()> + 'static + Send + Sync,

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

§Example
use rust_socketio::{asynchronous::ClientBuilder, Payload};
use futures_util::FutureExt;

 #[tokio::main]
async fn main() {
    let socket = ClientBuilder::new("http://localhost:4200/")
        .namespace("/admin")
        .on("test", |payload: Payload, _| {
            async move {
                match payload {
                    Payload::Text(values) => println!("Received: {:#?}", values),
                    Payload::Binary(bin_data) => println!("Received bytes: {:#?}", bin_data),
                    // This is deprecated, use Payload::Text instead
                    Payload::String(str) => println!("Received: {}", str),
                }
            }
            .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 rust_socketio::{asynchronous::ClientBuilder, Payload};
use futures_util::FutureExt;

#[tokio::main]
async fn main() {
    let callback = |payload: Payload, _| {
            async move {
                match payload {
                    Payload::Text(values) => println!("Received: {:#?}", values),
                    Payload::Binary(bin_data) => println!("Received bytes: {:#?}", bin_data),
                    // This is deprecated use Payload::Text instead
                    Payload::String(str) => println!("Received: {}", str),
                }
            }
            .boxed() // <-- this makes sure we end up with a `BoxFuture<_>`
        };

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

pub fn on_reconnect<F>(self, callback: F) -> Self
where F: for<'a> FnMut() -> BoxFuture<'static, ReconnectSettings> + 'static + Send + Sync,

Registers a callback for reconnect events. The event handler must return a ReconnectSettings struct with the settings that should be updated.

§Example
use rust_socketio::{asynchronous::{ClientBuilder, ReconnectSettings}};
use futures_util::future::FutureExt;
use serde_json::json;

#[tokio::main]
async fn main() {
    let client = ClientBuilder::new("http://localhost:4200/")
        .namespace("/admin")
        .on_reconnect(|| {
            async {
                let mut settings = ReconnectSettings::new();
                settings.address("http://server?test=123");
                settings.auth(json!({ "token": "abc" }));
                settings
            }.boxed()
        })
        .connect()
        .await;
}
source

pub fn on_any<F>(self, callback: F) -> Self
where F: for<'a> FnMut(Event, Payload, Client) -> BoxFuture<'static, ()> + 'static + Send + Sync,

Registers a Callback for all crate::event::Event::Custom and crate::event::Event::Message.

§Example
use rust_socketio::{asynchronous::ClientBuilder, Payload};
use futures_util::future::FutureExt;

#[tokio::main]
async fn main() {
    let client = ClientBuilder::new("http://localhost:4200/")
        .namespace("/admin")
        .on_any(|event, payload, _client| {
            async {
                if let Payload::String(str) = payload {
                    println!("{}: {}", String::from(event), str);
                }
            }.boxed()
        })
        .connect()
        .await;
}
source

pub fn tls_config(self, tls_config: TlsConnector) -> Self

Uses a preconfigured TLS connector for secure communication. This configures both the polling as well as the websocket transport type.

§Example
use rust_socketio::{asynchronous::ClientBuilder, Payload};
use native_tls::TlsConnector;
use futures_util::future::FutureExt;

#[tokio::main]
async fn main() {
    let tls_connector =  TlsConnector::builder()
               .use_sni(true)
               .build()
            .expect("Found illegal configuration");

    let socket = ClientBuilder::new("http://localhost:4200/")
        .namespace("/admin")
        .on("error", |err, _| async move { eprintln!("Error: {:#?}", err) }.boxed())
        .tls_config(tls_connector)
        .connect()
        .await;
}
source

pub fn opening_header<T: Into<HeaderValue>, K: Into<String>>( self, key: K, val: T ) -> Self

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 rust_socketio::{asynchronous::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;
}
source

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

Sets authentification data sent in the opening request.

§Example
use rust_socketio::{asynchronous::ClientBuilder};
use serde_json::json;
use futures_util::future::FutureExt;

#[tokio::main]
async fn main() {
    let socket = ClientBuilder::new("http://localhost:4204/")
        .namespace("/admin")
        .auth(json!({ "password": "1337" }))
        .on("error", |err, _| async move { eprintln!("Error: {:#?}", err) }.boxed())
        .connect()
        .await;
}
source

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

Specifies which EngineIO TransportType to use.

§Example
use rust_socketio::{asynchronous::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");
}
source

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

If set to false do not try to reconnect on network errors. Defaults to true

source

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

If set to true try to reconnect when the server disconnects the client. Defaults to false

source

pub fn reconnect_delay(self, min: u64, max: u64) -> Self

Sets the minimum and maximum delay between reconnection attempts

source

pub fn max_reconnect_attempts(self, reconnect_attempts: u8) -> Self

Sets the maximum number of times to attempt reconnections. Defaults to an infinite number of attempts

source

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

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 rust_socketio::{asynchronous::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());
}

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> Same for T

§

type Output = T

Should always be Self
source§

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

§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

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

§

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<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

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