Refactored broadcast code

This commit is contained in:
Adrian Victor 2024-11-13 09:57:49 -03:00
parent 3d607984d3
commit 72156a96ff
2 changed files with 37 additions and 32 deletions

6
config.json Normal file
View file

@ -0,0 +1,6 @@
{
"port": 4000,
"loginMessage": "Welcome to my Chatto server!",
"defaultUsername": "anonymous",
"serverNickname": "Server"
}

View file

@ -1,6 +1,7 @@
const config = require('./config.json')
import { WebSocket, WebSocketServer } from 'ws';
const wss = new WebSocketServer({ port: 4000 });
const wss = new WebSocketServer({ port: config.port });
type Client = {
ws: WebSocket;
@ -10,14 +11,31 @@ type Client = {
const clients: Client[] = [];
wss.on('connection', (ws) => {
const client: Client = { ws, nick: '' };
const client: Client = { ws, nick: config.defaultUsername };
clients.push(client);
const loginTimestamp = new Date().toLocaleTimeString();
ws.send (JSON.stringify({
loginTimestamp,
nick: "Server",
message: `Conectado ao servidor do Adrian.`
}))
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)
ws.on('message', (message) => {
const msg = message.toString();
@ -27,44 +45,25 @@ wss.on('connection', (ws) => {
const newNick = msg.split(' ')[1];
if (newNick) {
client.nick = newNick;
ws.send(JSON.stringify({
timestamp,
nick: 'Server',
message: `Nick set to ${newNick}`
}));
sendMessage(timestamp, `Nick set to ${newNick}`, config.serverNickname, false)
}
return
}
if (!client.nick) {
ws.send(JSON.stringify({
timestamp,
nick: 'Server',
message: 'You must set a nick first'
}));
sendMessage(timestamp, `You must set a nick first`, config.serverNickname, false)
return;
}
const broadcastMessage = JSON.stringify({
timestamp,
nick: client.nick,
message: msg
// message: msg.replace(/</g, '&lt;').replace(/>/g, '&gt;')
})
clients.forEach((c) => {
if (c.ws.readyState === WebSocket.OPEN)
c.ws.send(broadcastMessage);
});
sendMessage(timestamp, msg, client.nick)
});
// Remove client when connection is closed
// Removes client when connection is closed
ws.on('close', () => {
const index = clients.indexOf(client);
if (index !== -1)
clients.splice(index, 1);
});
});
console.log('Chatto WebSocket server is running on ws://localhost:4000');
console.log(`Chatto WebSocket server is running on ws://localhost:${config.port}`);