blitzchat/chatSocket.js

38 lines
1009 B
JavaScript
Raw Permalink Normal View History

const WebSocket = require('ws')
2019-11-26 15:08:24 +01:00
console.log('chatSocket is running on port 8082!');
2019-11-26 13:47:14 +01:00
2019-11-26 15:08:24 +01:00
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':
2019-11-26 13:47:14 +01:00
msg.color = 'black';
msg.style = 'bold';
break;
2019-11-26 13:47:14 +01:00
default:
msg.style = 'normal';
break;
}
2019-11-26 13:47:14 +01:00
msg.timestamp = new Date();
msg.msg = escapeHTML(msg.msg);
msg.username = escapeHTML(msg.username);
2019-11-25 14:55:55 +01:00
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(msg));
2019-11-25 14:55:55 +01:00
}
});
})
})
function escapeHTML(string) {
return string.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;')
.replace(/'/g, '&apos;');
}