blitzchat/chatSocket.js

38 lines
1009 B
JavaScript

const WebSocket = require('ws')
console.log('chatSocket is running on port 8082!');
const wss = new WebSocket.Server({port: 8082})
wss.on('connection', (ws) => {
ws.on('message', (data) => {
const msg = JSON.parse(data);
switch (msg.event) {
case 'joining':
msg.color = 'black';
msg.style = 'bold';
break;
default:
msg.style = 'normal';
break;
}
msg.timestamp = new Date();
msg.msg = escapeHTML(msg.msg);
msg.username = escapeHTML(msg.username);
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(msg));
}
});
})
})
function escapeHTML(string) {
return string.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}