Guide
Hooks
Using WebSocket hooks API, you can define a WebSocket server that works across runtimes with same synax.
CrossWS provides a cross-platform API to define WebSocket servers. An implementation with these hooks works across runtimes without needing you to go into details of any of them (while you always have the power to control low-level hooks). You can only define the life-cycle hooks that you only need and only those will be called on runtime.
CrossWS API is still under development and can change.
Using
defineHooks
to define hooks, we have type support and IDE auto-completion even if not using typescript. This utility does nothing more and you can use a plain object as well if you prefer to.import { defineHooks } from "crossws";
const hooks = defineHooks({
upgrade(req) {
console.log(`[ws] upgrading ${req.url}...`)
return {
headers: {}
}
}
open(peer) {
console.log(`[ws] open: ${peer}`);
},
message(peer, message) {
console.log("[ws] message", peer, message);
if (message.text().includes("ping")) {
peer.send("pong");
}
},
close(peer, event) {
console.log("[ws] close", peer, event);
},
error(peer, error) {
console.log("[ws] error", peer, error);
},
};