Module engineioxide::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, 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: String, socket: Arc<Socket<SocketState>>) {
*socket.data.id.lock().unwrap() = msg; // bind a provided user id to a socket
}
fn on_binary(&self, data: Vec<u8>, socket: Arc<Socket<SocketState>>) { }
}
let svc = EngineIoService::new(MyHandler::default());Structs
- A
Socketrepresents a client connection to the server. It is agnostic to theTransportType.
Enums
- A
DisconnectReasonrepresents the reason why aSocketwas closed.