Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to reply to the client and send a message if an error occures on accept_async funtion. #338

Closed
Zai-Kun opened this issue Jun 10, 2024 · 1 comment

Comments

@Zai-Kun
Copy link

Zai-Kun commented Jun 10, 2024

Hey there, I was wondering if there was a way to reply back to the client about the error that had occurred on accept_async but I can't figure out anyway to do so.
This is what I thought of at first:

    let ws_stream = if let Ok(ws_stream) = tokio_tungstenite::accept_async(stream).await {
        ws_stream
    } else {
        stream
            .write_all(&make_response(
                "Error, are you using a WS client?",
                "HTTP/1.1 400 Bad Request\r\n\r\n",
            ))
            .await
            .expect("Error while sending the msg");
        return;
    };

fn make_response(content: &str, status_line: &str) -> Vec<u8> {
    format!(
        "{}\r\nContent-Length: {}\r\n\r\n{}",
        status_line,
        content.len(),
        content
    )
    .as_bytes()
    .to_vec()
}

But as you can obviously see, the stream is moved to accept_async function thus cannot be used again. Is there any other way to achieve this? I looked through as many issues as I could but I couldn't an issue related to this. Thanks and sorry if this is dumb as I'm fairly new to rust and tokio-tungstenite.

@daniel-abramov
Copy link
Member

If you pass a stream to tokio-tungstenite, it will consume it (generally, there is no guarantee that the stream is usable after as often it's closed by the time you encounter an error).

However, if you're talking about a handshake phase only, this issue has been discussed here: snapview/tungstenite-rs#51

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants