mirror of
https://github.com/LukeHagar/crossws.git
synced 2025-12-09 20:37:49 +00:00
1.2 KiB
1.2 KiB
WebSocket 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.
import { defineWebSocketHooks } from "crossws";
const websocketHooks = defineWebSocketHooks({
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);
},
// ... platform hooks such as bun:drain ...
});
Note
Using
defineWebSocketHooksto 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.