Create Websocket Connection with Request Body

Hi.
I am using the crate tungsenite to learn about websocket.
In particular, I am interested in the connection to a websocket that requires a request body (for the secret).

Is tungsenite the appropriate crate to use? If so, can you provide sample code that makes a connection with request body.

So far the only example I have found is this ...

use tungstenite::{connect, Message};
use url::Url;

fn main() {
    env_logger::init();

    let (mut socket, response) =
        connect(Url::parse("ws://localhost:3012/socket")
                      .unwrap())
                      .expect("Can't connect");

    println!("Connected to the server");
    println!("Response HTTP code: {}", response.status());
    println!("Response contains the following headers:");
    for (ref header, _value) in response.headers() {
        println!("* {}", header);
    }

    socket.write_message(Message::Text("Hello WebSocket".into())).unwrap();
    loop {
        let msg = socket.read_message().expect("Error reading message");
        println!("Received: {}", msg);
    }
    // socket.close(None);
}

Please advise

When opening WebSocket handshake,

The method of the request MUST be GET

and

A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.

So in general it would be a bad idea. If you really need to do it, make sure no other middlewares like proxy/nginx/load balancer between your client and server as they may reject/discard such request on their own.

Thank you for your help. I understand now after your respond and learning more about rust!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.