websocket-relay/index.ts
2025-06-14 15:07:58 +02:00

42 lines
1.1 KiB
TypeScript

import {serve, ServerWebSocket} from "bun";
interface WSData {
room: string;
}
const PORT = 8080;
const MAIN_CHANNEL = "central";
const msg = (data: Record<string, unknown>) => JSON.stringify(data);
const server = serve({
fetch(req, server) {
const url = new URL(req.url);
const room = url.pathname.split("/")[1] ?? MAIN_CHANNEL;
if (server.upgrade(req, {data: {room}})) {
return;
}
return new Response("Upgrade failed :(", { status: 500 });
},
websocket: {
open(ws: ServerWebSocket<WSData>) {
const room = ws.data.room ?? MAIN_CHANNEL;
console.log(`${ws.remoteAddress} connected to '${room}' room`);
ws.subscribe(room);
},
message(ws, message) {
const room = ws.data.room ?? MAIN_CHANNEL;
ws.publish(room, message as unknown as BufferSource);
},
close(ws) {
const room = ws.data.room ?? MAIN_CHANNEL;
console.log(`${ws.remoteAddress} disconnected from '${room}' room`);
ws.unsubscribe(room);
ws.publish(room, msg({message: "someone left"}));
},
},
port: PORT,
});
console.log(`Listening on ${server.hostname}:${server.port}`);