如何使用 tokio-tungstenite 进行超时阻塞读取?

问题描述 投票:0回答:1

是否有一个简单的 API 可以在读取 tokio-tungstenite 中的下一条 websocket 消息时超时阻止?

现在,我有:

read.next().await
其中 read 是
SplitStream<WebSocketStream<MaybeTlsStream<TcpStream>>>
这将“永远”阻塞,直到收到消息或错误(例如操作系统强制关闭套接字)。

我想做的是

read.next(timeout).await
,它要么等待消息/错误,要么在超时后放弃。

有什么办法可以做到这一点吗?

rust rust-tokio tungstenite
1个回答
0
投票

[tokio][1]
有一个
[timeout][1]
函数,它将在超时时阻塞
[Future][1]
。 它确实创建了一些需要解构的嵌套。例如:

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
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.