How to reply to the client and send a message if an error occures on `accept_async` funtion.
Zai-Kun opened this issue · 1 comments
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.
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