basic connection and naming

This commit is contained in:
Baipyrus 2023-01-17 19:15:50 +01:00
parent 0c593d1019
commit 031541b1fe

View File

@ -1,18 +1,72 @@
const logging = true;
const fs = require('fs');
const http = require('http');
const crypto = require('crypto');
const express = require('express');
const app = express();
const clientPath = __dirname+'/../html';
const clientPath = __dirname+'/../../Websites/TerminalHomepage';
console.log('Serving static from ' + clientPath);
app.use(express.json());
app.use(express.static(clientPath));
const server = http.createServer(app);
const users = [];
app.get('/connect', (req, res) => {
const id = crypto.randomUUID();
users.push({
socket: req.socket,
date: new Date(),
name: "",
id
});
if (logging)
console.log(`User connected with ID '${id}'.`);
res.status(200).json({ id });
});
app.post('/disconnect', (req, res) => {
const { id } = req.body;
for (let i = 0; i < users.length; i++)
if (users[i].id === id) {
if (logging)
console.log(`User with ID '${id}' disconnected.`);
users.splice(i, 1);
break;
}
res.status(200).send();
});
app.post('/nickname', (req, res) => {
const { id, name } = req.body;
for (const u of users)
if (u.id === id) {
if (logging)
console.log(`(Re-)named user with ID '${id}'!`);
u.name = name;
break;
}
res.status(200).send();
});
app.post('/message', (req, res) => {
const { id, message } = req.body;
console.log(`User '${id}' sent message '${message}'.`);
res.status(200).json({message});
let name = "";
for (const u of users)
if (u.id === id) {
name = u.name;
break;
}
let user = `User '${name}'`;
if (!name)
user = name = "Anonymous"
if (logging) {
const idStr = (!name) ? ` ID: ${id}.` : '';
console.log(`${user} sent message '${message}'.${idStr}`);
}
res.status(200).json({ message });
});
server.on('error', err => {