pub struct Connection {
pub id: ConnectionId,
pub info: ConnectionInfo,
/* private fields */
}Expand description
Represents an active WebSocket connection.
A Connection provides methods to send messages to the connected client.
Messages are sent asynchronously through an unbounded channel, ensuring
that slow clients don’t block the server.
§Thread Safety
Connection is cheaply cloneable (uses Arc internally) and can be
safely shared across threads.
§Examples
§Sending Text Messages
use wsforge::prelude::*;
// Send a text message
conn.send_text("Hello, client!")?;
// Send JSON data
#[derive(serde::Serialize)]
struct Response {
status: String,
data: i32,
}
conn.send_json(&Response {
status: "ok".to_string(),
data: 42,
})?;§Sending Binary Data
use wsforge::prelude::*;
let data = vec![0x01, 0x02, 0x03, 0x04];
conn.send_binary(data)?;Fields§
§id: ConnectionIdUnique identifier for this connection
info: ConnectionInfoConnection metadata
Implementations§
Source§impl Connection
impl Connection
Sourcepub fn new(
id: ConnectionId,
addr: SocketAddr,
sender: UnboundedSender<Message>,
) -> Self
pub fn new( id: ConnectionId, addr: SocketAddr, sender: UnboundedSender<Message>, ) -> Self
Creates a new Connection instance.
This is typically called internally by the framework when a new WebSocket connection is established.
§Arguments
id- Unique identifier for the connectionaddr- Socket address of the clientsender- Channel sender for outgoing messages
§Examples
use wsforge::connection::Connection;
use tokio::sync::mpsc;
use std::net::SocketAddr;
let (tx, rx) = mpsc::unbounded_channel();
let addr: SocketAddr = "127.0.0.1:8080".parse().unwrap();
let conn = Connection::new("conn_0".to_string(), addr, tx);
assert_eq!(conn.id(), "conn_0");Sourcepub fn send(&self, message: Message) -> Result<()>
pub fn send(&self, message: Message) -> Result<()>
Sends a message to the connected client.
Messages are queued in an unbounded channel and sent asynchronously. This method returns immediately without waiting for the message to be sent.
§Errors
Returns an error if the connection has been closed and the channel receiver has been dropped.
§Examples
use wsforge::prelude::*;
let msg = Message::text("Hello!");
conn.send(msg)?;Sourcepub fn send_json<T: Serialize>(&self, data: &T) -> Result<()>
pub fn send_json<T: Serialize>(&self, data: &T) -> Result<()>
Serializes data to JSON and sends it as a text message.
This is a convenience method for sending structured data. The data
is serialized using serde_json and sent as a text message.
§Errors
Returns an error if:
- Serialization fails
- The connection has been closed
§Examples
use wsforge::prelude::*;
use serde::Serialize;
#[derive(Serialize)]
struct GameState {
score: u32,
level: u8,
}
let state = GameState { score: 1000, level: 5 };
conn.send_json(&state)?;Sourcepub fn id(&self) -> &ConnectionId
pub fn id(&self) -> &ConnectionId
Returns the unique identifier for this connection.
§Examples
use wsforge::prelude::*;
println!("Connection ID: {}", conn.id());Sourcepub fn info(&self) -> &ConnectionInfo
pub fn info(&self) -> &ConnectionInfo
Returns the connection metadata.
§Examples
use wsforge::prelude::*;
let info = conn.info();
println!("Client address: {}", info.addr);
println!("Connected at: {}", info.connected_at);Trait Implementations§
Source§impl Clone for Connection
impl Clone for Connection
Source§impl FromMessage for Connection
Extractor for the active connection.
impl FromMessage for Connection
Extractor for the active connection.
Provides access to the connection that sent the message, allowing you to:
- Get the connection ID
- Access connection metadata
- Send messages back to the specific client
§Examples
§Sending Response
use wsforge::prelude::*;
async fn handler(msg: Message, conn: Connection) -> Result<()> {
conn.send_text("Message received!")?;
Ok(())
}§Using Connection Info
use wsforge::prelude::*;
async fn handler(conn: Connection) -> Result<String> {
let info = conn.info();
Ok(format!("Client from {} connected at {}",
info.addr, info.connected_at))
}Source§fn from_message<'life0, 'life1, 'life2, 'life3, 'async_trait>(
_message: &'life0 Message,
conn: &'life1 Connection,
_state: &'life2 AppState,
_extensions: &'life3 Extensions,
) -> Pin<Box<dyn Future<Output = Result<Self>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
'life3: 'async_trait,
fn from_message<'life0, 'life1, 'life2, 'life3, 'async_trait>(
_message: &'life0 Message,
conn: &'life1 Connection,
_state: &'life2 AppState,
_extensions: &'life3 Extensions,
) -> Pin<Box<dyn Future<Output = Result<Self>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
'life1: 'async_trait,
'life2: 'async_trait,
'life3: 'async_trait,
Self from the message and context. Read more