blitzchat/chatSocket.js

87 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

2020-03-16 11:51:28 +01:00
const WebSocket = require("ws");
2019-11-27 14:06:27 +01:00
const port = 8082;
2019-11-26 13:47:14 +01:00
2019-11-27 14:06:27 +01:00
console.log(`chatSocket is running on port ${port}!`);
2020-03-16 11:51:28 +01:00
const wss = new WebSocket.Server({ port: port });
2019-11-27 14:06:27 +01:00
function noop() {}
2020-03-16 11:51:28 +01:00
2019-11-27 14:06:27 +01:00
function heartbeat() {
this.isAlive = true;
}
2020-03-16 11:51:28 +01:00
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);
2020-03-16 11:51:28 +01:00
stringMsg = JSON.stringify(msg);
sendAll(stringMsg);
});
});
2019-11-27 14:06:27 +01:00
const interval = setInterval(function ping() {
2020-03-16 11:51:28 +01:00
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);
2019-11-27 14:06:27 +01:00
function getAllUsers() {
2020-03-16 11:51:28 +01:00
let users = [];
wss.clients.forEach(ws => {
users.push(ws.username);
});
if (users.length > 0) {
console.log("following users are online: " + users);
}
return users;
2019-11-27 14:06:27 +01:00
}
function sendAll(stringMsg) {
2020-03-16 11:51:28 +01:00
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(stringMsg);
}
});
2019-11-27 14:06:27 +01:00
}
function escapeHTML(string) {
2020-03-16 11:51:28 +01:00
return string
.replace(/&/g, "&")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;")
.replace(/'/g, "&apos;");
}