Guide
Pub / Sub
crossws supports native pub-sub API integration. A peer can be subscribed to a set of named channels using peer.subscribe(<name>)
. Messages can be published to a channel using peer.publish(<name>, <message>)
.
import { defineHooks } from "crossws";
const hooks = defineHooks({
open(peer) {
// Send welcome to the new client
peer.send("Welcome to the server!");
// Join new client to the "chat" channel
peer.subscribe("chat");
// Notify every other connected client
peer.publish("chat", `[system] ${peer} joined!`);
},
message(peer, message) {
// The server re-broadcasts incoming messages to everyone
peer.publish("chat", `[${peer}] ${message}`);
},
close(peer) {
peer.publish("chat", `[system] ${peer} has left the chat!`);
peer.unsubscribe("chat");
},
});