Event Handling and SocketContext Reference
As with web controllers, Socket.IO controllers work with struct methods, and each method can use a general context extractor.
This struct, called SocketContext, holds information about the connection, the event, and the socket state.
API Reference: Methods of the 'SocketContext' struct
Accessing the socket identifier
pub fn id(&self) -> &SidReturns
- The
&Sidthat identifies this socket.
When to use it
- Logging, tracing, and linking events to a specific connection.
Checking whether the socket is connected
Checks whether the socket is still active before running operations that depend on the connection.
pub fn connected(&self) -> boolReturns
trueorfalsedepending on whether the socket is connected.
Accessing the socket namespace
pub fn ns(&self) -> &strReturns
- The namespace path of this socket.
Accessing the socket rooms
pub fn rooms(&self) -> Vec<Room>Returns
- Every room name this socket is connected to.
Accessing the current event name
pub fn event(&self) -> Option<&str>Returns
Some(event_name)in message handlers.
INFO
When you call this method in the connection or disconnection event, it returns None.
Accessing the disconnect reason
pub fn disconnect_reason(&self) -> Option<&DisconnectReason>Returns
Some(reason)in disconnection handlers.Noneinconnect/message.
When to use it
- Auditing why a connection was closed.
Accessing the protocol version in use
pub fn protocol_version(&self) -> ProtocolVersionReturns
- The negotiated Socket.IO protocol version.
When to use it
- Diagnostics and client compatibility checks.
Accessing the transport type in use
pub fn transport_type(&self) -> TransportTypeReturns
- The active transport (
websocketorpolling).
When to use it
- Telemetry, transport-specific rules, and handshake debugging.
Accessing the event payload
pub fn try_data<T: DeserializeOwned>(&self) -> Result<T, SocketError>Parameters
Tis the expected data type. It must implementDeserializeOwned.
Returns
Ok(T)if the payload was deserialized.Err(SocketError)if no payload is available or parsing fails.
INFO
In the connection event, this method tries to read the auth payload from the handshake.
WARNING
This method consumes the internal payload. A second call in the same handler fails.
Accessing the event payload with validation
pub fn try_data_validator<T>(&self) -> Result<T, SocketError>
where
T: DeserializeOwned + ValidateReturns
Ok(T)if the payload deserializes and validates.Err(SocketError)if parsing fails, no payload is available, or validation fails.
When to use it
- When the payload must follow schema validation rules.
INFO
In the connection event, this method tries to read the auth payload from the handshake.
WARNING
This method consumes the internal payload. A second call in the same handler fails.
Checking whether a payload is available
pub fn has_data(&self) -> boolReturns
trueif the payload has not been consumed yet.
When to use it
- To avoid parsing the same payload twice.
Accessing the URL query parameters
pub fn query<T: DeserializeOwned>(&self) -> Result<Option<T>, SocketError>Parameters
Tis the expected data type. It must implementDeserializeOwned.
Returns
Ok(Some(T))if the query string exists and is valid.Ok(None)if there is no query string.Err(SocketError)if the query exists but cannot be deserialized.
When to use it
- To read URL query parameters during the connection.
Emitting an event to the client
pub fn emit<T>(&self, event: impl AsRef<str>, data: &T) -> Result<(), SocketError>
where
T: Serialize + ?SizedParameters
eventis the name of the event to emit.datais the serializable payload to send.
Returns
Ok(())if the event is sent.Err(SocketError)if sending fails.
When to use it
- To send events to the connected client.
Emitting an event to the client and waiting for confirmation
pub fn emit_with_ack<T: ?Sized + Serialize, V>(
&self,
event: impl AsRef<str>,
data: &T,
) -> Result<AckStream<V>, SocketError>Parameters
eventis the name of the event to emit.datais the serializable payload to send.
Returns
- An
AckStreamthat resolves when the client confirms the event.
When to use it
- When you need the client to confirm that it received the event.
Accessing a broadcast operator
pub fn broadcast(&self) -> BroadcastOperators<A>Returns
- A broadcast operator that sends to every connected client except the sender.
When to use it
- To send a message to every connected client.
Accessing a broadcast operator limited to specific rooms
pub fn to(&self, rooms: impl RoomParam) -> BroadcastOperators<A>Returns
- A broadcast operator limited to the specified rooms.
When to use it
- To send to specific rooms the socket belongs to.
Accessing a broadcast operator that excludes certain rooms
pub fn except(&self, rooms: impl RoomParam) -> BroadcastOperators<A>Returns
- A broadcast operator that excludes the specified rooms.
When to use it
- To broadcast to everyone except certain rooms.
Accessing a configuration operator for acknowledgements
pub fn timeout(&self, timeout: Duration) -> ConfOperators<'_, A>Returns
- A configuration operator with a custom timeout for the acknowledgement.
When to use it
- To set a timeout when sending a message with confirmation.
Adding the socket to one or more rooms
pub fn join(&self, rooms: impl RoomParam)When to use it
- To add the current socket to one or more rooms.
Removing the socket from one or more rooms
pub fn leave(&self, rooms: impl RoomParam)When to use it
- To remove the current socket from one or more rooms.
Removing the socket from all its rooms
pub fn leave_all(&self)When to use it
- To remove the current socket from all its rooms.
Checking whether the current event includes an ACK callback
pub fn has_ack(&self) -> boolReturns
trueif the current event includes an ACK callback.
When to use it
- Before calling
ack(...)in message handlers.
Responding to a client ACK callback
pub fn ack<D>(self, data: &D) -> Result<(), SendError>
where
D: Serialize + ?SizedParameters
datais the serializable payload to send as the callback response.
Returns
Ok(())if the ACK is sent.Err(SendError)if no ACK is available or sending fails.
When to use it
- To answer client callbacks when
has_ack()istrue.
When not to use it
- In handlers without an associated ACK.
WARNING
It consumes self, so you cannot reuse the context after calling it.
Getting the HTTP request parts from the initial handshake
pub fn req_parts(&self) -> &PartsReturns
- The HTTP request parts from the initial handshake.
When to use it
- To access raw HTTP data such as the method or URI.
Getting the HTTP headers from the initial handshake
pub fn headers(&self) -> &HeaderMapReturns
- A reference to the socket request headers.
When to use it
- To read HTTP headers from the initial handshake.
Getting the 'Authorization' header from the initial handshake
pub fn authorization(&self) -> Option<&str>Returns
- The
Authorizationheader value, if present.
When to use it
- To extract Bearer tokens or other authentication data from the handshake.
Accessing the socket extensions store
pub fn extensions(&self) -> &ExtensionsReturns
- The extensions store associated with the socket.
When to use it
- To share state during the connection.
Accessing the HTTP extensions store from the initial handshake
pub fn http_extensions(&self) -> &HttpExtensionsReturns
- The HTTP extensions from the initial handshake.
When to use it
- To reuse data written by HTTP interceptors or layers during the handshake.
Closing the socket connection
pub fn disconnect(self) -> Result<(), SocketError>Returns
Ok(())if the disconnection runs.Err(SocketError)if closing the connection fails.
When to use it
- When the server decides to close the connection itself.
WARNING
It consumes self, so you cannot reuse the context after calling it.
Base example
use sword::prelude::*;
use sword::socketio::*;
#[controller(kind = Controller::SocketIo, namespace = "/chat")]
pub struct ChatController;
impl ChatController {
#[on("connection")]
async fn on_connect(&self, socket: SocketContext) {
println!("connected: {}", socket.id());
let query: Option<MyQuery> = socket.query().unwrap();
}
#[on("message")]
async fn on_message(&self, socket: SocketContext) {
let Ok(message) = socket.try_data::<String>() else {
return;
};
if socket.has_ack() {
let _ = socket.ack(&"ok");
return;
}
socket.emit("message", &message).ok();
}
#[on("disconnection")]
async fn on_disconnect(&self, socket: SocketContext) {
println!("reason: {:?}", socket.disconnect_reason());
}
}
