pub struct WebSocketConnection { /* private fields */ }Expand description
WebSocket connection with activity tracking and timeout support
Implementations§
Source§impl WebSocketConnection
impl WebSocketConnection
Sourcepub fn new(id: String, tx: UnboundedSender<Message>) -> Self
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");Sourcepub fn with_config(
id: String,
tx: UnboundedSender<Message>,
config: ConnectionConfig,
) -> Self
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));Sourcepub fn with_subprotocol(
id: String,
tx: UnboundedSender<Message>,
subprotocol: Option<String>,
) -> Self
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"));Sourcepub fn subprotocol(&self) -> Option<&str>
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"));Sourcepub fn id(&self) -> &str
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");Sourcepub fn config(&self) -> &ConnectionConfig
pub fn config(&self) -> &ConnectionConfig
Gets the connection timeout configuration.
Sourcepub async fn record_activity(&self)
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);Sourcepub async fn idle_duration(&self) -> Duration
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));Sourcepub async fn is_idle(&self) -> bool
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);Sourcepub async fn send(&self, message: Message) -> WebSocketResult<()>
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 { .. }));Sourcepub async fn send_text(&self, text: String) -> WebSocketResult<()>
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"),
}Sourcepub async fn send_binary(&self, data: Vec<u8>) -> WebSocketResult<()>
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"),
}Sourcepub async fn send_json<T: Serialize>(&self, data: &T) -> WebSocketResult<()>
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"),
}Sourcepub async fn close(&self) -> WebSocketResult<()>
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);Sourcepub async fn close_with_reason(
&self,
code: u16,
reason: String,
) -> WebSocketResult<()>
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"),
}Sourcepub async fn force_close(&self)
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);Sourcepub async fn is_closed(&self) -> bool
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);