gloo_net/websocket/
mod.rs

1//! Wrapper around `WebSocket` API
2//!
3//! This API is provided in the following flavors:
4//! - [Futures API][futures]
5
6pub mod events;
7pub mod futures;
8
9#[cfg(feature = "io-util")]
10mod io_util;
11
12use events::CloseEvent;
13use gloo_utils::errors::JsError;
14use std::fmt;
15
16/// Message sent to and received from WebSocket.
17#[derive(Debug, PartialEq, Eq, Clone)]
18pub enum Message {
19    /// String message
20    Text(String),
21    /// ArrayBuffer parsed into bytes
22    Bytes(Vec<u8>),
23}
24
25/// The state of the websocket.
26///
27/// See [`WebSocket.readyState` on MDN](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState)
28/// to learn more.
29#[derive(Copy, Clone, Debug)]
30pub enum State {
31    /// The connection has not yet been established.
32    Connecting,
33    /// The WebSocket connection is established and communication is possible.
34    Open,
35    /// The connection is going through the closing handshake, or the close() method has been
36    /// invoked.
37    Closing,
38    /// The connection has been closed or could not be opened.
39    Closed,
40}
41
42/// Error returned by WebSocket
43#[derive(Debug)]
44#[non_exhaustive]
45pub enum WebSocketError {
46    /// The `error` event
47    ConnectionError,
48    /// The `close` event
49    ConnectionClose(CloseEvent),
50    /// Message failed to send.
51    MessageSendError(JsError),
52}
53
54impl fmt::Display for WebSocketError {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            WebSocketError::ConnectionError => write!(f, "WebSocket connection failed"),
58            WebSocketError::ConnectionClose(e) => write!(
59                f,
60                "WebSocket Closed: code: {}, reason: {}",
61                e.code, e.reason
62            ),
63            WebSocketError::MessageSendError(e) => write!(f, "{e}"),
64        }
65    }
66}
67
68impl std::error::Error for WebSocketError {}