Is there a straightforward API to block with timeout on reading the next websocket message in tokio-tungstenite?
Right now, I have:
read.next().await
where read is a SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>
This will block "forever" until it receives a message or error (eg. OS forces the socket closed).
What I'd like to do is read.next(timeout).await
which will either wait for a message/error, or it will give up after the timeout.
Is there some way to do this?
tokio has a function timeout(Duration, F:Future) that will block on a Future with a timeout. This particular case creates a bit of nesting to be destructured. For example:
match timeout(Duration::from_secs(100), read.next()).await {
Err(elapsed) => // timed out
Ok(None) => // read.next returned None
Ok(Some(msg)) => match msg {
Ok(Message::Text(text)) => //
// ...
Err(e) => // Error receiving the message
}
}