leptos_use

Function use_websocket

Source
pub fn use_websocket<Tx, Rx, C>(
    url: &str,
) -> UseWebSocketReturn<Tx, Rx, impl Fn() + Clone + 'static, impl Fn() + Clone + 'static, impl Fn(&Tx) + Clone + 'static>
where Tx: 'static, Rx: 'static, C: Encoder<Tx> + Decoder<Rx> + HybridEncoder<Tx, <C as Encoder<Tx>>::Encoded, Error = <C as Encoder<Tx>>::Error> + HybridDecoder<Rx, <C as Decoder<Rx>>::Encoded, Error = <C as Decoder<Rx>>::Error>,
Expand description

Creating and managing a Websocket connection.

§Demo

Link to Demo

§Usage

Values are (en)decoded via the given codec. You can use any of the codecs, string or binary.

Please check the codec chapter to see what codecs are available and what feature flags they require.

let UseWebSocketReturn {
    ready_state,
    message,
    send,
    open,
    close,
    ..
} = use_websocket::<String, String, FromToStringCodec>("wss://echo.websocket.events/");

let send_message = move |_| {
    send(&"Hello, world!".to_string());
};

let status = move || ready_state.get().to_string();

let connected = move || ready_state.get() == ConnectionReadyState::Open;

let open_connection = move |_| {
    open();
};

let close_connection = move |_| {
    close();
};

view! {
    <div>
        <p>"status: " {status}</p>

        <button on:click=send_message disabled=move || !connected()>"Send"</button>
        <button on:click=open_connection disabled=connected>"Open"</button>
        <button on:click=close_connection disabled=move || !connected()>"Close"</button>

        <p>"Receive message: " {move || format!("{:?}", message.get())}</p>
    </div>
}

Here is another example using msgpack for encoding and decoding. This means that only binary messages can be sent or received. For this to work you have to enable the msgpack_serde feature flag.

#[derive(Serialize, Deserialize)]
struct SomeData {
    name: String,
    count: i32,
}

let UseWebSocketReturn {
    message,
    send,
    ..
} = use_websocket::<SomeData, SomeData, MsgpackSerdeCodec>("wss://some.websocket.server/");

let send_data = move || {
    send(&SomeData {
        name: "John Doe".to_string(),
        count: 42,
    });
};
}

§Relative Paths

If the provided url is relative, it will be resolved relative to the current page. Urls will be resolved like this the following. Please note that the protocol (http vs https) will be taken into account as well.

Current PageRelative UrlResolved Url
http://example.com/some/where/api/wsws://example.com/api/ws
https://example.com/some/where/api/wswss://example.com/api/ws
https://example.com/some/whereapi/wswss://example.com/some/where/api/ws
https://example.com/some/where//otherdomain.com/api/wswss://otherdomain.com/api/ws

§Usage with provide_context

The return value of use_websocket utilizes several type parameters which can make it cumbersome to use with provide_context + expect_context. The following example shows how to avoid type parameters with dynamic dispatch. This sacrifices a little bit of performance for the sake of ergonomics. However, compared to network transmission speeds this loss of performance is negligible.

First we define the struct that is going to be passed around as context.

use std::rc::Rc;

#[derive(Clone)]
pub struct WebsocketContext {
    pub message: Signal<Option<String>>,
    send: Rc<dyn Fn(&String)>,  // use Rc to make it easily cloneable
}

impl WebsocketContext {
    pub fn new(message: Signal<Option<String>>, send: Rc<dyn Fn(&String)>) -> Self {
        Self {
            message,
            send,
        }
    }

    // create a method to avoid having to use parantheses around the field
    #[inline(always)]
    pub fn send(&self, message: &str) {
        (self.send)(&message.to_string())
    }
}

Now you can provide the context like the following.


let UseWebSocketReturn {
    message,
    send,
    ..
} = use_websocket::<String, String, FromToStringCodec>("ws:://some.websocket.io");

provide_context(WebsocketContext::new(message, Rc::new(send.clone())));

Finally let’s use the context:


let websocket = expect_context::<WebsocketContext>();

websocket.send("Hello World!");

§Server-Side Rendering

On the server the returned functions amount to no-ops.