snapview / tokio-tungstenite

Future-based Tungstenite for Tokio. Lightweight stream-based WebSocket implementation
MIT License
1.88k stars 236 forks source link

How get the current state of the WebSocket connection? #258

Closed A-kirami closed 1 year ago

A-kirami commented 1 year ago

Hi, I need to confirm the current state of the WebSocket connection.

What should I do? Thanks!

daniel-abramov commented 1 year ago

Sorry, I did not get the question. What do you mean by the state of the WebSocket connection?

A-kirami commented 1 year ago

Like WebSocket.readyState in JavaScript.

https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState

daniel-abramov commented 1 year ago

Once you get a WebSocket object (e.g. after awaiting on a connect), it's guaranteed to be in an already connected state (unlike JavaScript, Rust supports ADTs, so we don't need an enum to describe a state, a state is explicit in our case). And you can assume that it's connected up until the stream of messages closes or returns an error. Once the error is returned, the WebSocket will continue to be closed (an attempt to write to such a connection or read from it would return an error).

But if you prefer a short enum to describe the connection state, you could always introduce an additional variable for that or wrap the WebSocket, i.e. something like:

enum WebSocketState {
    Connecting(<your future here>),
    Connected(WebSocketStream),
    Closed,
}

Or use something similar.