Module message

Module message 

Source
Expand description

WebSocket message types and utilities.

This module provides the core message abstraction used throughout WsForge. It wraps the underlying WebSocket message types from tokio-tungstenite and provides convenient methods for creating, inspecting, and parsing messages.

§Overview

WebSocket messages can be one of several types:

  • Text: UTF-8 encoded string data
  • Binary: Raw byte data
  • Ping/Pong: Control frames for keep-alive
  • Close: Connection termination frames

The Message type provides a unified interface for working with all these types, with automatic conversion between WsForge’s message type and the underlying tungstenite message type.

§Message Types

TypeDescriptionUse Case
MessageType::TextUTF-8 textJSON, commands, chat messages
MessageType::BinaryRaw bytesImages, files, protocol buffers
MessageType::PingKeep-alive requestConnection health checks
MessageType::PongKeep-alive responseResponding to pings
MessageType::CloseConnection closeGraceful disconnection

§Examples

§Creating Messages

use wsforge::prelude::*;

// Text message
let text_msg = Message::text("Hello, WebSocket!");

// Binary message
let binary_msg = Message::binary(vec![0x01, 0x02, 0x03]);

// JSON message (text)
let json_msg = Message::text(r#"{"type":"greeting","text":"hello"}"#);

§Inspecting Messages

use wsforge::prelude::*;

if msg.is_text() {
    println!("Text: {}", msg.as_text().unwrap());
} else if msg.is_binary() {
    println!("Binary: {} bytes", msg.as_bytes().len());
}

// Get the message type
match msg.message_type() {
    MessageType::Text => println!("Received text"),
    MessageType::Binary => println!("Received binary"),
    _ => println!("Received control frame"),
}

§Parsing JSON

use wsforge::prelude::*;
use serde::Deserialize;

#[derive(Deserialize)]
struct ChatMessage {
    username: String,
    text: String,
}

// Parse JSON from message
let chat: ChatMessage = msg.json()?;
println!("{} says: {}", chat.username, chat.text);

Structs§

Message
A WebSocket message.

Enums§

MessageType
Represents the type of a WebSocket message.