Question: Can Websocket Handlers Receive Ping/Pong/Close Messages? #1340
-
👋 Hi! Thanks for your work on Axum. I have a question about a documentation ambiguity. I'm testing out using Axum for an application that primarily communicates with clients via Websockets. So far things are working well, but one thing I'm a bit confused about is which of the In particular, I currently have a function that tries to read the next message of a websocket and parse it into an app-specific structure. That function looks like: async fn read_from_websocket<'a, T: serde::de::DeserializeOwned>(
ws: &mut SplitStream<WebSocket>,
) -> Result<T, WebsocketReadError> {
loop {
match ws.next().await {
Some(Ok(Message::Text(s))) => {
return serde_json::from_str(&s).map_err(Into::into);
}
Some(Ok(Message::Binary(_))) => {
return Err(WebsocketReadError::UnexpectedBinaryMessage);
}
Some(Ok(msg)) => {
// XXX: Do we need to handle non-Text/Binary messages?[
continue;
}
Some(Err(e)) => {
return Err(WebsocketReadError::from(e));
}
None => {
return Err(WebsocketReadError::Closed);
}
}
}
} At the points in my protocol where I'm calling this, I expect the next received message to be a regular text message containing some json that I can parse into my type. If I get an unexpected message type I want to return an error indicating what went wrong. One issue I'm having it is that it's unclear to me whether I should expect to receive
but it wasn't clear to me if this means that Axum will filter out Ping messages and handle them before they even get to me, or if it just means that Axum will queue Pongs before forwarding to me, but I'm still responsible for ignoring Pong messages in my application. I have similar questions for whether my application needs to explicitly ignore Pong/Close messages. Thanks in advance for your time! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
axum uses tungstenite internally to do all the websocket stuff and tungstenite will automatically respond to pings. See snapview/tokio-tungstenite#88. So you just ignore them. |
Beta Was this translation helpful? Give feedback.
axum uses tungstenite internally to do all the websocket stuff and tungstenite will automatically respond to pings. See snapview/tokio-tungstenite#88. So you just ignore them.