Connection

Struct Connection 

Source
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: ConnectionId

Unique identifier for this connection

§info: ConnectionInfo

Connection metadata

Implementations§

Source§

impl Connection

Source

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 connection
  • addr - Socket address of the client
  • sender - 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");
Source

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)?;
Source

pub fn send_text(&self, text: impl Into<String>) -> Result<()>

Sends a text message to the connected client.

This is a convenience method that creates a text Message and sends it.

§Errors

Returns an error if the connection has been closed.

§Examples
use wsforge::prelude::*;

conn.send_text("Welcome to the chat!")?;
Source

pub fn send_binary(&self, data: Vec<u8>) -> Result<()>

Sends binary data to the connected client.

This is a convenience method that creates a binary Message and sends it.

§Errors

Returns an error if the connection has been closed.

§Examples
use wsforge::prelude::*;

let data = vec![0xFF, 0xFE, 0xFD];
conn.send_binary(data)?;
Source

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)?;
Source

pub fn id(&self) -> &ConnectionId

Returns the unique identifier for this connection.

§Examples
use wsforge::prelude::*;

println!("Connection ID: {}", conn.id());
Source

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

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

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,

Extracts Self from the message and context. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more