pub struct WsSender { /* private fields */ }Expand description
WebSocket sender for server-push messaging.
Allows WebSocket handlers to send messages to the client independently of the request/response cycle, enabling true bidirectional communication.
§Automatic Injection
Methods in #[ws] impl blocks can receive a WsSender parameter that is
automatically injected:
ⓘ
use server_less::{ws, WsSender};
#[ws(path = "/chat")]
impl ChatService {
async fn join_room(&self, sender: WsSender, room: String) -> String {
// Store sender for later use
self.rooms.add_user(room, sender);
"Joined room".to_string()
}
async fn broadcast(&self, room: String, message: String) {
// Send to all users in room (senders stored earlier)
for sender in self.rooms.get_senders(&room) {
sender.send_json(&json!({"type": "broadcast", "msg": message})).await.ok();
}
}
}§Thread Safety
WsSender is cheaply cloneable (via Arc) and thread-safe, so you can:
- Store it in application state
- Clone and send it to background tasks
- Share it across threads
ⓘ
// Clone and use in background task
let sender_clone = sender.clone();
tokio::spawn(async move {
sender_clone.send("Background message").await.ok();
});Implementations§
Source§impl WsSender
impl WsSender
Sourcepub async fn send_json<T>(&self, value: &T) -> Result<(), String>where
T: Serialize,
pub async fn send_json<T>(&self, value: &T) -> Result<(), String>where
T: Serialize,
Send a JSON value to the WebSocket client
The value is serialized to JSON and sent as a text message.
§Errors
Returns an error if serialization fails or the connection is closed.
§Example
ⓘ
use serde_json::json;
sender.send_json(&json!({
"type": "notification",
"message": "New message received"
})).await?;Trait Implementations§
Auto Trait Implementations§
impl Freeze for WsSender
impl !RefUnwindSafe for WsSender
impl Send for WsSender
impl Sync for WsSender
impl Unpin for WsSender
impl UnsafeUnpin for WsSender
impl !UnwindSafe for WsSender
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more