Play with sockets
This commit is contained in:
Vendored
+1
@@ -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": {
|
||||||
|
|||||||
@@ -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;
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user