Skip to main content

WebSocketConnection

Struct WebSocketConnection 

Source
pub struct WebSocketConnection { /* private fields */ }
Expand description

WebSocket connection with activity tracking and timeout support

Implementations§

Source§

impl WebSocketConnection

Source

pub fn new(id: String, tx: UnboundedSender<Message>) -> Self

Creates a new WebSocket connection with the given ID and sender.

Uses default ConnectionConfig for timeout settings.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, _rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("connection_1".to_string(), tx);
assert_eq!(conn.id(), "connection_1");
Source

pub fn with_config( id: String, tx: UnboundedSender<Message>, config: ConnectionConfig, ) -> Self

Creates a new WebSocket connection with the given ID, sender, and configuration.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use reinhardt_websockets::connection::ConnectionConfig;
use tokio::sync::mpsc;
use std::time::Duration;

let (tx, _rx) = mpsc::unbounded_channel();
let config = ConnectionConfig::new()
    .with_idle_timeout(Duration::from_secs(60));
let conn = WebSocketConnection::with_config("conn_1".to_string(), tx, config);
assert_eq!(conn.id(), "conn_1");
assert_eq!(conn.config().idle_timeout(), Duration::from_secs(60));
Source

pub fn with_subprotocol( id: String, tx: UnboundedSender<Message>, subprotocol: Option<String>, ) -> Self

Creates a new WebSocket connection with the given ID, sender, and subprotocol.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, _rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::with_subprotocol(
    "connection_1".to_string(),
    tx,
    Some("chat".to_string())
);
assert_eq!(conn.id(), "connection_1");
assert_eq!(conn.subprotocol(), Some("chat"));
Source

pub fn subprotocol(&self) -> Option<&str>

Gets the negotiated subprotocol, if any.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, _rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::with_subprotocol(
    "test".to_string(),
    tx,
    Some("chat".to_string())
);
assert_eq!(conn.subprotocol(), Some("chat"));
Source

pub fn id(&self) -> &str

Gets the connection ID.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, _rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test_id".to_string(), tx);
assert_eq!(conn.id(), "test_id");
Source

pub fn config(&self) -> &ConnectionConfig

Gets the connection timeout configuration.

Source

pub async fn record_activity(&self)

Records activity on the connection, resetting the idle timer.

This is called automatically when sending messages, but can also be called manually to indicate that the connection is still active (e.g., when receiving messages from the client).

§Examples
use reinhardt_websockets::WebSocketConnection;
use tokio::sync::mpsc;

let (tx, _rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

conn.record_activity().await;
assert!(!conn.is_idle().await);
Source

pub async fn idle_duration(&self) -> Duration

Returns the duration since the last activity on this connection.

§Examples
use reinhardt_websockets::WebSocketConnection;
use tokio::sync::mpsc;
use std::time::Duration;

let (tx, _rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

let idle = conn.idle_duration().await;
assert!(idle < Duration::from_secs(1));
Source

pub async fn is_idle(&self) -> bool

Checks whether this connection has exceeded its idle timeout.

§Examples
use reinhardt_websockets::WebSocketConnection;
use tokio::sync::mpsc;

let (tx, _rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

// A freshly created connection is not idle
assert!(!conn.is_idle().await);
Source

pub async fn send(&self, message: Message) -> WebSocketResult<()>

Sends a message through the WebSocket connection.

Records activity on the connection when a message is sent successfully.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, mut rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

let message = Message::text("Hello".to_string());
conn.send(message).await.unwrap();

let received = rx.recv().await.unwrap();
assert!(matches!(received, Message::Text { .. }));
Source

pub async fn send_text(&self, text: String) -> WebSocketResult<()>

Sends a text message through the WebSocket connection.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, mut rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

conn.send_text("Hello World".to_string()).await.unwrap();

let received = rx.recv().await.unwrap();
match received {
    Message::Text { data } => assert_eq!(data, "Hello World"),
    _ => panic!("Expected text message"),
}
Source

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

Sends a binary message through the WebSocket connection.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, mut rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

let binary_data = vec![0x48, 0x65, 0x6c, 0x6c, 0x6f]; // "Hello"
conn.send_binary(binary_data.clone()).await.unwrap();

let received = rx.recv().await.unwrap();
match received {
    Message::Binary { data } => assert_eq!(data, binary_data),
    _ => panic!("Expected binary message"),
}
Source

pub async fn send_json<T: Serialize>(&self, data: &T) -> WebSocketResult<()>

Sends a JSON message through the WebSocket connection.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;
use serde::Serialize;

#[derive(Serialize)]
struct User {
    name: String,
    age: u32,
}

let (tx, mut rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

let user = User { name: "Alice".to_string(), age: 30 };
conn.send_json(&user).await.unwrap();

let received = rx.recv().await.unwrap();
match received {
    Message::Text { data } => assert!(data.contains("Alice")),
    _ => panic!("Expected text message"),
}
Source

pub async fn close(&self) -> WebSocketResult<()>

Closes the WebSocket connection.

The connection is always marked as closed regardless of whether the close frame could be sent. This ensures resource cleanup even when the underlying channel is already broken.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, mut rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

conn.close().await.unwrap();
assert!(conn.is_closed().await);
Source

pub async fn close_with_reason( &self, code: u16, reason: String, ) -> WebSocketResult<()>

Closes the connection with a custom close code and reason.

The connection is always marked as closed regardless of whether the close frame could be sent. This ensures resource cleanup even when the underlying channel is already broken.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, mut rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

conn.close_with_reason(1001, "Idle timeout".to_string()).await.unwrap();
assert!(conn.is_closed().await);

let msg = rx.recv().await.unwrap();
match msg {
    Message::Close { code, reason } => {
        assert_eq!(code, 1001);
        assert_eq!(reason, "Idle timeout");
    },
    _ => panic!("Expected close message"),
}
Source

pub async fn force_close(&self)

Forces the connection closed without sending a close frame.

Use this for abnormal close paths where the underlying transport is already broken and sending a close frame would fail.

§Examples
use reinhardt_websockets::WebSocketConnection;
use tokio::sync::mpsc;

let (tx, _rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

conn.force_close().await;
assert!(conn.is_closed().await);
Source

pub async fn is_closed(&self) -> bool

Checks if the WebSocket connection is closed.

§Examples
use reinhardt_websockets::{WebSocketConnection, Message};
use tokio::sync::mpsc;

let (tx, _rx) = mpsc::unbounded_channel();
let conn = WebSocketConnection::new("test".to_string(), tx);

assert!(!conn.is_closed().await);

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> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

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, 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