const WebSocket = require("ws"); const port = 8082; console.log(`chatSocket is running on port ${port}!`); const wss = new WebSocket.Server({ port: port }); function noop() {} function heartbeat() { this.isAlive = true; } wss.on("connection", ws => { ws.isAlive = true; ws.on("pong", heartbeat); ws.on("message", data => { const msg = JSON.parse(data); switch (msg.event) { case "joining": msg.color = "black"; msg.style = "bold"; ws.username = msg.username; break; default: msg.style = "normal"; break; } msg.timestamp = new Date(); msg.msg = escapeHTML(msg.msg); msg.username = escapeHTML(msg.username); stringMsg = JSON.stringify(msg); sendAll(stringMsg); }); }); const interval = setInterval(function ping() { const users = getAllUsers(); wss.clients.forEach(function each(ws) { if (ws.isAlive === false) { console.log(ws.username, " has left"); return ws.terminate(); } ws.isAlive = false; ws.ping(noop); let msg = { event: "users", msg: users, timestamp: Date.now() }; ws.send(JSON.stringify(msg)); }); }, 10000); function getAllUsers() { let users = []; wss.clients.forEach(ws => { users.push(ws.username); }); if (users.length > 0) { console.log("following users are online: " + users); } return users; } function sendAll(stringMsg) { wss.clients.forEach(function each(client) { if (client.readyState === WebSocket.OPEN) { client.send(stringMsg); } }); } function escapeHTML(string) { return string .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """) .replace(/'/g, "'"); }