Now we know

This commit is contained in:
Daniel Flanagan 2021-11-17 08:52:25 -06:00
parent a1636ff2f5
commit 6d608b6f0e
Signed by: lytedev
GPG key ID: 5B2020A0F9921EF4
4 changed files with 48 additions and 55 deletions

20
gen.ts
View file

@ -1,20 +0,0 @@
const ALFNUM = "0123456789";
const SECRET_LENGTH = 8;
function randomInt(low: number, high: number) {
return Math.floor(Math.random() * (high - low + 1) + low);
}
export function randomId() {
const arr = new Int32Array(1);
crypto.getRandomValues(arr);
return Math.abs(arr[0]);
}
export function randomSecret() {
let out = "";
for (let i = 0; i < SECRET_LENGTH; i++) {
out += ALFNUM[randomInt(0, ALFNUM.length - 1)];
}
return out;
}

View file

@ -4,7 +4,9 @@
# Signalling Server
The signaling server is written in TypeScript to run on Deno. It can run in the
Requires Deno >= 1.16.1
The signaling server is written in TypeScript to run on Deno (1.16.1). It can run in the
cloud via Deno deploy.
PORT=8888 deno run --allow-env --allow-net server.ts

View file

@ -21,9 +21,14 @@ const lobbies = new Set<Lobby>();
const clients = new Set<Client>();
console.log("Listening on port", PORT);
for await (const conn of Deno.listen({ port: PORT })) {
const listener = Deno.listen({ port: PORT });
for await (const conn of listener) {
console.debug("Connection received:", conn);
(async () => {
for await (const { respondWith, request } of Deno.serveHttp(conn)) {
const server = Deno.serveHttp(conn);
for await (const { respondWith, request } of server) {
console.debug("HTTP Request Received", request);
try {
const { socket, response } = Deno.upgradeWebSocket(request);
const client: Client = { socket };
socket.onmessage = (ev) => {
@ -31,7 +36,7 @@ for await (const conn of Deno.listen({ port: PORT })) {
};
socket.onopen = (ev) => {
console.log("New Client:", ev);
clients.add(client);
if (!clients.has(client)) clients.add(client);
socket.send("lobbies_start");
lobbies.forEach(({ name, clients }) => {
socket.send(JSON.stringify({ name, numClients: clients.length }));
@ -40,13 +45,28 @@ for await (const conn of Deno.listen({ port: PORT })) {
};
socket.onclose = (ev) => {
console.log("Client Socket Close:", ev);
clients.delete(client);
if (clients.has(client)) clients.delete(client);
};
socket.onerror = (ev) => {
console.log("Client Socket Error:", ev);
clients.delete(client);
if (clients.has(client)) clients.delete(client);
};
respondWith(response);
} catch (e) {
let body = "400 Bad Request";
if (e instanceof TypeError) {
body += " - Expected to be able to upgrade to WebSocket connection";
console.log("Could not add client:", e);
} else {
console.log("Could not add client for unhandled reason:", e);
}
respondWith(
new Response(body, {
status: 400,
headers: { "content-type": "text/html" },
}),
);
}
}
})();
}

View file

@ -1,9 +0,0 @@
export interface Client {
socket: WebSocket;
}
export interface Lobby {
name: string;
secret: string;
clients: Client[];
}