1

Is there any way/example to establish web socket connection through off chain worker? There are many Rust examples but I can't use standard library.

Can someone please help me?

1 Answer 1

2

Find a relevant package that works in no-std context, for example, embedded-websocket.

I managed to establish ws connection to a Substrate chain with the following code:

fn offchain_worker(_now: BlockNumberFor<T>) {
    let ws_port = "ws://127.0.0.1:9999";
    log::info!("Connecting to: {}", ws_port);

    let websocket_options = embedded_websocket::WebSocketOptions {
        path: "",
        host: "localhost",
        origin: "http://localhost:9999",
        sub_protocols: None,
        additional_headers: None,
    };

    let mut read_buf = [0u8; 4000];
    let mut handshake_buf = [0u8; 4000];

    let mut websocket = WebSocketClient::new_client(embedded_websocket::random::EmptyRng::new());

    let result = websocket.client_connect(&websocket_options, &mut handshake_buf);

    log::info!("Connected. {:?}", result);
}

This logs the following:

2023-12-14 23:22:48 Connecting to: ws://127.0.0.1:9999    
2023-12-14 23:22:48 Connected. Ok((204, "AAAAAAAAAAAAAAAAAAAAAA=="))   

And afaiu, you can then pass whatever request you want via websocket.write(). For example (not tested code):

let json_string = r#"{"jsonrpc":"2.0","method":"chain_getBlockHash","params":[1],"id":1}"#;

let num_bytes = websocket.write(
    WebSocketSendMessageType::Text,
    true,
    json_string.as_bytes(),
    &mut read_buf,
);

Use the package at your own risk, bit it seems it does the job.

4
  • Use HTTP would be much better I think.
    – AurevoirXavier
    Commented Dec 15, 2023 at 10:18
  • for connecting to the Substrate node, yes, for sure. But OP asked specifically about establishing WS connection in offchain-worker, so I suggested this and used WS connection to the node as an example
    – dastansam
    Commented Dec 15, 2023 at 10:41
  • @dastansam Did you use read and write module as well?
    – Boleng
    Commented Dec 19, 2023 at 11:33
  • @dastansam Even with this library, we can't bind and open web socket server. We have to use TcpListener and TcpStream, which are available in Rust standard library. Please let me know if I am missing anything.
    – Boleng
    Commented Dec 20, 2023 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.