Play with sockets

This commit is contained in:
Schluffe
2026-09-10 22:46:50 +02:00
parent e961887953
commit a7a48ae8fe
2 changed files with 41 additions and 0 deletions
+1
View File
@@ -1,6 +1,7 @@
{ {
"bun.debugTerminal.enabled": true, "bun.debugTerminal.enabled": true,
"bun.debugTerminal.stopOnEntry": false, "bun.debugTerminal.stopOnEntry": false,
"deno.enable": true,
"editor.formatOnSave": true, "editor.formatOnSave": true,
"editor.defaultFormatter": "biomejs.biome", "editor.defaultFormatter": "biomejs.biome",
"editor.codeActionsOnSave": { "editor.codeActionsOnSave": {
+40
View File
@@ -0,0 +1,40 @@
/// <reference lib="deno.ns" />
const clientsMap = new Map<number, WebSocket>();
let nextId = 1;
const handleConnection = (socket: WebSocket): void => {
const id = nextId++;
socket.onopen = () => {
clientsMap.set(id, socket);
broadcast(`${id} has joined!`);
};
socket.onclose = () => {
clientsMap.delete(id);
broadcast(`${id} has left!`);
};
socket.onmessage = console.log;
socket.onerror = console.error;
};
function broadcast(message: string): void {
for (const socket of clientsMap.values()) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(message);
}
}
}
Deno.serve({ port: 6969 }, (request) => {
if (request.headers.get("upgrade") !== "websocket") {
return new Response("Upgrade Required", { status: 426 });
}
const { socket, response } = Deno.upgradeWebSocket(request);
handleConnection(socket);
return response;
});