pub struct Message {
pub data: Vec<u8>,
pub msg_type: MessageType,
}Expand description
A WebSocket message.
This is the main type for working with WebSocket messages in WsForge. It wraps the raw message data and provides convenient methods for creating, inspecting, and converting messages.
§Thread Safety
Message is cheaply cloneable and can be safely shared across threads.
§Examples
§Creating Messages
use wsforge::prelude::*;
// Create text message
let greeting = Message::text("Hello!");
// Create binary message
let data = Message::binary(vec!);[1][2][3][4]§Working with Content
use wsforge::prelude::*;
// Check message type
if msg.is_text() {
// Get text content
if let Some(text) = msg.as_text() {
println!("Message: {}", text);
}
}
// Get raw bytes (works for both text and binary)
let bytes = msg.as_bytes();
println!("Size: {} bytes", bytes.len());Fields§
§data: Vec<u8>The raw message data as bytes.
For text messages, this contains UTF-8 encoded text. For binary messages, this contains raw bytes.
msg_type: MessageTypeThe type of this message.
Implementations§
Source§impl Message
impl Message
Sourcepub fn text(text: impl Into<String>) -> Self
pub fn text(text: impl Into<String>) -> Self
Creates a new text message.
The string is converted to UTF-8 bytes and stored as a text message.
§Arguments
text- The text content (any type convertible toString)
§Examples
use wsforge::prelude::*;
// From &str
let msg1 = Message::text("Hello");
// From String
let msg2 = Message::text(String::from("World"));
// From format!
let msg3 = Message::text(format!("User {} joined", 42));Sourcepub fn binary(data: Vec<u8>) -> Self
pub fn binary(data: Vec<u8>) -> Self
Creates a new binary message.
The bytes are stored as-is without any encoding or processing.
§Arguments
data- The binary data
§Examples
use wsforge::prelude::*;
// From Vec<u8>
let msg1 = Message::binary(vec![0x01, 0x02, 0x03]);
// From byte slice
let bytes: &[u8] = &[0xFF, 0xFE, 0xFD];
let msg2 = Message::binary(bytes.to_vec());
// From array
let msg3 = Message::binary(.to_vec());[2][3][4][1]Sourcepub fn ping(data: Vec<u8>) -> Self
pub fn ping(data: Vec<u8>) -> Self
Creates a ping message.
Ping messages are used for connection keep-alive. The client should respond with a pong message (handled automatically by most WebSocket implementations).
§Arguments
data- Optional payload data (usually empty)
§Examples
use wsforge::prelude::*;
// Simple ping
let ping = Message::ping(vec![]);
// Ping with payload
let ping_with_data = Message::ping(b"timestamp:1234567890".to_vec());Sourcepub fn pong(data: Vec<u8>) -> Self
pub fn pong(data: Vec<u8>) -> Self
Creates a pong message.
Pong messages are sent in response to ping messages. This is typically handled automatically by the framework.
§Arguments
data- Payload data (should match the ping payload)
§Examples
use wsforge::prelude::*;
// Respond to a ping
if ping_msg.is_ping() {
let pong = Message::pong(ping_msg.data.clone());
// Send pong back...
}Sourcepub fn close() -> Self
pub fn close() -> Self
Creates a close message.
Close messages signal graceful connection termination. The connection will close after this message is sent/received.
§Examples
use wsforge::prelude::*;
// Simple close
let close = Message::close();Sourcepub fn into_tungstenite(self) -> TungsteniteMessage
pub fn into_tungstenite(self) -> TungsteniteMessage
Converts this message to a tungstenite message.
This is used internally by the framework to convert between WsForge’s message type and the underlying WebSocket library.
§Examples
use wsforge::prelude::*;
let msg = Message::text("Hello");
let tungstenite_msg = msg.into_tungstenite();Sourcepub fn from_tungstenite(msg: TungsteniteMessage) -> Self
pub fn from_tungstenite(msg: TungsteniteMessage) -> Self
Creates a message from a tungstenite message.
This is used internally by the framework to convert incoming WebSocket messages to WsForge’s message type.
§Arguments
msg- A tungstenite WebSocket message
§Examples
use wsforge::prelude::*;
use tokio_tungstenite::tungstenite::Message as TungsteniteMessage;
let tung_msg = TungsteniteMessage::Text("Hello".to_string());
let msg = Message::from_tungstenite(tung_msg);
assert!(msg.is_text());Sourcepub fn message_type(&self) -> MessageType
pub fn message_type(&self) -> MessageType
Returns the type of this message.
§Examples
use wsforge::prelude::*;
let msg = Message::text("Hello");
assert_eq!(msg.message_type(), MessageType::Text);
let binary = Message::binary(vec!);[3][1][2]
assert_eq!(binary.message_type(), MessageType::Binary);Sourcepub fn is_text(&self) -> bool
pub fn is_text(&self) -> bool
Checks if this is a text message.
§Examples
use wsforge::prelude::*;
if msg.is_text() {
println!("Processing text: {}", msg.as_text().unwrap());
}Sourcepub fn is_binary(&self) -> bool
pub fn is_binary(&self) -> bool
Checks if this is a binary message.
§Examples
use wsforge::prelude::*;
if msg.is_binary() {
let bytes = msg.as_bytes();
println!("Processing {} bytes of binary data", bytes.len());
}Sourcepub fn is_ping(&self) -> bool
pub fn is_ping(&self) -> bool
Checks if this is a ping message.
§Examples
use wsforge::prelude::*;
if msg.is_ping() {
// Framework usually auto-responds with pong
println!("Received ping");
}Sourcepub fn is_pong(&self) -> bool
pub fn is_pong(&self) -> bool
Checks if this is a pong message.
§Examples
use wsforge::prelude::*;
if msg.is_pong() {
println!("Connection is alive");
}Sourcepub fn is_close(&self) -> bool
pub fn is_close(&self) -> bool
Checks if this is a close message.
§Examples
use wsforge::prelude::*;
if msg.is_close() {
println!("Client is disconnecting");
}Sourcepub fn as_text(&self) -> Option<&str>
pub fn as_text(&self) -> Option<&str>
Returns the message content as a string slice, if it’s a text message.
Returns None if the message is not text or if the data is not valid UTF-8.
§Examples
use wsforge::prelude::*;
if let Some(text) = msg.as_text() {
println!("Received: {}", text);
}Sourcepub fn as_bytes(&self) -> &[u8] ⓘ
pub fn as_bytes(&self) -> &[u8] ⓘ
Returns the message content as a byte slice.
This works for all message types, returning the raw underlying data.
§Examples
use wsforge::prelude::*;
let bytes = msg.as_bytes();
println!("Message size: {} bytes", bytes.len());
// Works for text messages too
let text_msg = Message::text("Hello");
assert_eq!(text_msg.as_bytes(), b"Hello");Sourcepub fn json<T: DeserializeOwned>(&self) -> Result<T>
pub fn json<T: DeserializeOwned>(&self) -> Result<T>
Deserializes the message content as JSON.
This is a convenience method for parsing JSON from text messages.
The type must implement serde::Deserialize.
§Errors
Returns an error if:
- The message is not text
- The JSON is malformed
- The JSON doesn’t match the expected type
§Examples
§Simple Types
use wsforge::prelude::*;
let msg = Message::text(r#"{"name":"Alice","age":30}"#);
let value: serde_json::Value = msg.json()?;
assert_eq!(value["name"], "Alice");§Struct Deserialization
use wsforge::prelude::*;
use serde::Deserialize;
#[derive(Deserialize)]
struct User {
name: String,
age: u32,
}
let msg = Message::text(r#"{"name":"Alice","age":30}"#);
let user: User = msg.json()?;
assert_eq!(user.name, "Alice");Trait Implementations§
Source§impl FromMessage for Message
Extractor for the raw message.
impl FromMessage for Message
Extractor for the raw message.
Use this when you need access to the complete message without automatic deserialization.
§Examples
§Raw Message Processing
use wsforge::prelude::*;
async fn handler(msg: Message) -> Result<String> {
if msg.is_text() {
Ok(format!("Text: {}", msg.as_text().unwrap()))
} else if msg.is_binary() {
Ok(format!("Binary: {} bytes", msg.as_bytes().len()))
} else {
Ok("Unknown message type".to_string())
}
}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 moreSource§impl IntoResponse for Message
Response that sends the message as-is.
impl IntoResponse for Message
Response that sends the message as-is.
Use this when you have full control over the message construction.
§Examples
use wsforge::prelude::*;
async fn custom_handler() -> Result<Message> {
Ok(Message::text("Custom response"))
}