Skip to main content

Message Channels

Channels let you logically separate different types of messages within a session. Use named channels to organize traffic by purpose -- for example, "chat" for user messages, "presence" for online/offline status, and "sync" for data synchronization.

Default Channel

Messages sent without a channel name go to the default channel. All subscribers receive default channel messages.

session.send("", b"sent on default channel").await?;

Named Channels

Named channels allow logical separation of message types. Pass a channel name as the first argument to send:

session.send("chat", b"hello").await?;
session.send("presence", b"online").await?;
session.send("sync", b"{\"key\": \"value\"}").await?;

Subscribing to Channels

Handle incoming messages and filter by channel name:

let mut events = node.subscribe();
while let Some(event) = events.recv().await {
match event {
Event::MessageReceived { peer_id, channel, data } => {
match channel.as_str() {
"chat" => println!("Chat from {}: {}", peer_id, String::from_utf8_lossy(&data)),
"presence" => println!("{} is {}", peer_id, String::from_utf8_lossy(&data)),
"sync" => handle_sync(&data),
_ => {}
}
}
_ => {}
}
}

Binary vs Text Data

Channels support both binary and text data. The data parameter accepts bytes in all languages:

LanguageBinary TypeExample
Rust&[u8]b"raw bytes"
TypeScriptBufferBuffer.from('text')
Go[]byte[]byte("text")
Pythonbytesb"raw bytes"
PHPstring'text' (PHP strings are binary-safe)

Sending binary data (e.g., a file chunk):

let image_bytes = std::fs::read("photo.png")?;
session.send("file", &image_bytes).await?;