Message

Struct Message 

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

The type of this message.

Implementations§

Source§

impl Message

Source

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 to String)
§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));
Source

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]
Source

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

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...
}
Source

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

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

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

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

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());
}
Source

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());
}
Source

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");
}
Source

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");
}
Source

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");
}
Source

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

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

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 Clone for Message

Source§

fn clone(&self) -> Message

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 Debug for Message

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

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,

Extracts Self from the message and context. Read more
Source§

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"))
}
Source§

fn into_response<'async_trait>( self, ) -> Pin<Box<dyn Future<Output = Result<Option<Message>>> + Send + 'async_trait>>
where Self: 'async_trait,

Converts this value into an optional message. 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