blitzchat/static/websocket.js

108 lines
2.4 KiB
JavaScript
Raw Permalink Normal View History

2019-11-27 11:41:48 +01:00
var ws;
2019-11-27 14:06:27 +01:00
const port = 8082;
function heartbeat() {
2020-03-16 11:51:28 +01:00
clearTimeout(this.pingTimeout);
2019-11-27 14:06:27 +01:00
2020-03-16 11:51:28 +01:00
this.pingTimeout = setTimeout(() => {
ws.terminate();
}, 30000 + 3000);
2019-11-27 14:06:27 +01:00
}
2020-03-16 11:51:28 +01:00
ws.on("ping", heartbeat);
2019-11-27 11:41:48 +01:00
2020-03-16 11:51:28 +01:00
function send(e) {
e.preventDefault();
const msg = {
event: "msg",
msg: document.getElementById("text").value,
username: document.getElementById("username").value,
color: document.getElementById("color").value
};
ws.send(JSON.stringify(msg));
document.getElementById("text").value = "";
2019-11-27 11:41:48 +01:00
}
function join(e) {
2020-03-16 11:51:28 +01:00
e.preventDefault();
2019-11-27 11:41:48 +01:00
2020-03-16 11:51:28 +01:00
document.getElementById("joinButton").remove();
document.getElementById("username").setAttribute("readonly", "");
2019-11-27 11:41:48 +01:00
2020-03-16 11:51:28 +01:00
ws = new WebSocket("ws://" + window.location.hostname + `:${port}`);
ws.onopen = () => {
heartbeat();
const msg = {
event: "joining",
msg: "",
username: document.getElementById("username").value,
color: "black"
};
const msgString = JSON.stringify(msg);
ws.send(msgString);
};
2019-11-27 11:41:48 +01:00
2020-03-16 11:51:28 +01:00
ws.onmessage = msg => {
const jsonObj = JSON.parse(msg.data);
2019-11-27 11:41:48 +01:00
2020-03-16 11:51:28 +01:00
const chat = document.getElementById("chat");
2019-11-27 11:41:48 +01:00
2020-03-16 11:51:28 +01:00
if (jsonObj.event === "joining") {
chat.innerHTML += getMessageSpan(
jsonObj,
jsonObj.username + " has joined the chat!"
);
} else if (jsonObj.event === "msg") {
chat.innerHTML +=
getTime(new Date(jsonObj.timestamp)) +
'<span style="font-weight: bold">' +
jsonObj.username +
"</span>" +
": " +
getMessageSpan(jsonObj, jsonObj.msg);
} else {
console.log(jsonObj);
}
2019-11-27 11:41:48 +01:00
2020-03-16 11:51:28 +01:00
// scroll to the bottom of the chat
chat.scrollTop = chat.scrollHeight;
};
2019-11-27 11:41:48 +01:00
2020-03-16 11:51:28 +01:00
ws.onclose = msg => {
const chat = document.getElementById("chat");
chat.innerHTML += "<b>Connection Closed</b>";
clearTimeout(this.pingTimeout);
};
2019-11-27 11:41:48 +01:00
2020-03-16 11:51:28 +01:00
function getTime(date) {
let hours = date.getHours();
let minutes = date.getMinutes();
if (hours < 10) {
hours = "0" + hours;
2019-11-27 11:41:48 +01:00
}
2020-03-16 11:51:28 +01:00
if (minutes < 10) {
minutes = "0" + minutes;
2019-11-27 11:41:48 +01:00
}
2020-03-16 11:51:28 +01:00
return (
'<span style="color: lightgray; font-weight: lighter" >' +
hours +
":" +
minutes +
" </span>"
);
}
function getMessageSpan(jsonObj, innerMessage) {
return (
'<span style="color:' +
jsonObj.color +
"; font-weight: " +
jsonObj.style +
'" >' +
innerMessage +
"</span>" +
"<br>"
);
}
}