chatto/server.ts

69 lines
1.9 KiB
TypeScript
Raw Normal View History

2024-11-13 13:57:49 +01:00
const config = require('./config.json')
2024-11-12 15:55:37 +01:00
import { WebSocket, WebSocketServer } from 'ws';
2024-11-13 13:57:49 +01:00
const wss = new WebSocketServer({ port: config.port });
2024-11-12 15:55:37 +01:00
type Client = {
ws: WebSocket;
nick: string;
}
const clients: Client[] = [];
wss.on('connection', (ws) => {
2024-11-13 13:57:49 +01:00
const client: Client = { ws, nick: config.defaultUsername };
2024-11-12 15:55:37 +01:00
clients.push(client);
2024-11-13 13:57:49 +01:00
function sendMessage(timestamp: string, message: string, nickname: string, isPublic: boolean = true) {
if (!isPublic) {
ws.send (JSON.stringify({
timestamp,
nick: nickname,
message: message
}))
} else {
// message: msg.replace(/</g, '&lt;').replace(/>/g, '&gt;') // uncomment this and change the argument passed to sendMessage() to disable HTML injection
clients.forEach((c) => {
if (c.ws.readyState === WebSocket.OPEN)
c.ws.send (JSON.stringify({
timestamp,
nick: nickname,
message: message
}))
});
}
}
const loginTimestamp = new Date().toLocaleTimeString()
sendMessage(loginTimestamp, config.loginMessage, config.serverNickname, false)
2024-11-12 15:55:37 +01:00
ws.on('message', (message) => {
const msg = message.toString();
const timestamp = new Date().toLocaleTimeString();
if (msg.startsWith('/nick ')) {
const newNick = msg.split(' ')[1];
if (newNick) {
client.nick = newNick;
2024-11-13 13:57:49 +01:00
sendMessage(timestamp, `Nick set to ${newNick}`, config.serverNickname, false)
2024-11-12 15:55:37 +01:00
}
return
}
if (!client.nick) {
2024-11-13 13:57:49 +01:00
sendMessage(timestamp, `You must set a nick first`, config.serverNickname, false)
2024-11-12 15:55:37 +01:00
return;
}
2024-11-13 13:57:49 +01:00
sendMessage(timestamp, msg, client.nick)
2024-11-12 15:55:37 +01:00
});
2024-11-13 13:57:49 +01:00
// Removes client when connection is closed
2024-11-12 15:55:37 +01:00
ws.on('close', () => {
const index = clients.indexOf(client);
if (index !== -1)
clients.splice(index, 1);
});
});
2024-11-13 13:57:49 +01:00
console.log(`Chatto WebSocket server is running on ws://localhost:${config.port}`);