Rust/websocket idiomatic restart

  1. This is wasm32 code written in Rust. I have this so far:
    fn setup_ws_handler(&self) {

        let ws = WebSocket::new("ws://127.0.0.1:3012").unwrap();

        ws.add_event_listener( move |_: SocketOpenEvent| {
            let msg = format!("Connection Opened");
            console!(log, msg);
        });

        ws.add_event_listener( move |_: SocketErrorEvent| {
            let msg = format!("Connection Errored");
            console!(log, msg);
        });

        ws.add_event_listener( move |event: SocketCloseEvent| {
            let msg = format!("Connection Closed: {:?}", event.reason());
            console!(log, msg);
        });

        ws.add_event_listener( move |event: SocketMessageEvent| {
            let data = &event.data().into_text().unwrap();
            let to_client: ToClient = serde_json::from_str(data).unwrap() ;
            let msg = format!("we need to process: {:?}", to_client);
            console!(log, msg);
            // write_my_msg(ToClient(to_client));
        });



  1. Now, because networks can be unreliable, the ws can die any time. I want the ws to try to reconnect whenever that happens. What is the idiomatic way to do this? The goal is:

(2a) If we have an active ws connection, do nothing.
(2b) If we do not have an active ws connection, try to reconnect continuously, but only once at a time.

Perhaps you just need to store the connection state on the parent type. When the connection is successfully open, update the state. When the connection is dropped, update the state and call a method to reconnect as needed.

When you need to reconnect, you can set the state to reflect such so that you don’t call reconnect multiple times. Lots of ways to model this behavior. Hope that helps.