engineioxide

Module socket

Source
Expand description

§A Socket represents a client connection to the server

It can be used to :

  • Emit binary or string data
  • Get a reference to the request made to connect to the socket.io server
  • Close the connection
§Example :
// Global state
#[derive(Debug, Default)]
struct MyHandler {
    user_cnt: AtomicUsize,
}

// Socket state
#[derive(Debug, Default)]
struct SocketState {
    id: Mutex<String>,
}

impl EngineIoHandler for MyHandler {
    type Data = SocketState;

    fn on_connect(self: Arc<Self>, socket: Arc<Socket<SocketState>>) {
        // Get the request made to initialize the connection
        // and check that the authorization header is correct
        let connected = socket.req_parts.headers.get("Authorization")
            .map(|a| a == "mysuperpassword!").unwrap_or_default();
        // Close the socket if the authentication is invalid
        if !connected {
            socket.close(DisconnectReason::TransportError);
            return;
        }

        let cnt = self.user_cnt.fetch_add(1, Ordering::Relaxed) + 1;
        // Emit string data to the client
        socket.emit(cnt.to_string()).ok();
    }
    fn on_disconnect(&self, socket: Arc<Socket<SocketState>>, reason: DisconnectReason) {
        let cnt = self.user_cnt.fetch_sub(1, Ordering::Relaxed) - 1;
    }
    fn on_message(&self, msg: Str, socket: Arc<Socket<SocketState>>) {
        *socket.data.id.lock().unwrap() = msg.into(); // bind a provided user id to a socket
    }
    fn on_binary(&self, data: Bytes, socket: Arc<Socket<SocketState>>) { }
}

let svc = EngineIoService::new(Arc::new(MyHandler::default()));

Structs§

  • A permit to emit a message to the client. A permit holds a place in the internal channel to send one packet to the client.
  • A Socket represents a client connection to the server. It is agnostic to the TransportType.

Enums§