Skip to main content

zero_client/client/
socket.rs

1//! What the engine sees of a WebSocket: it opens one per connection
2//! attempt, sends text frames, and is told about frames and the close. This
3//! is the shape of the browser `WebSocket` the JS client uses.
4
5use std::rc::Rc;
6
7/// A frame from the server.
8#[derive(Clone, Debug, PartialEq, Eq)]
9pub enum SocketMessage {
10    /// A text frame.
11    Text(String),
12    /// A binary frame.
13    Binary(Vec<u8>),
14}
15
16/// Opens the sync socket. Every call is on the engine's thread.
17pub trait SocketFactory {
18    /// Starts opening a WebSocket to `url`, sending `sec_protocol` (when
19    /// set) as the `Sec-WebSocket-Protocol` header. Events go to `events`
20    /// until the engine closes the socket.
21    fn open(
22        &self,
23        url: &str,
24        sec_protocol: Option<&str>,
25        events: Rc<dyn SocketEvents>,
26    ) -> Box<dyn SocketConnection>;
27}
28
29/// An open or opening WebSocket.
30pub trait SocketConnection {
31    /// Sends a text frame.
32    fn send(&self, text: &str);
33    /// Closes the socket. No more events are delivered after this.
34    fn close(&self, code: Option<u16>);
35}
36
37/// Receives the events of one socket.
38pub trait SocketEvents {
39    /// The socket opened.
40    fn did_open(&self);
41    /// A frame arrived.
42    fn did_receive(&self, message: SocketMessage);
43    /// The socket closed, with its close code and reason; `was_clean` when the
44    /// closing handshake finished.
45    fn did_close(&self, code: u16, reason: &str, was_clean: bool);
46}