var ws; const port = 8082; function heartbeat() { clearTimeout(this.pingTimeout); this.pingTimeout = setTimeout(() => { ws.terminate(); }, 30000 + 3000); } ws.on("ping", heartbeat); 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 = ""; } function join(e) { e.preventDefault(); document.getElementById("joinButton").remove(); document.getElementById("username").setAttribute("readonly", ""); 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); }; ws.onmessage = msg => { const jsonObj = JSON.parse(msg.data); const chat = document.getElementById("chat"); 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)) + '' + jsonObj.username + "" + ": " + getMessageSpan(jsonObj, jsonObj.msg); } else { console.log(jsonObj); } // scroll to the bottom of the chat chat.scrollTop = chat.scrollHeight; }; ws.onclose = msg => { const chat = document.getElementById("chat"); chat.innerHTML += "Connection Closed"; clearTimeout(this.pingTimeout); }; function getTime(date) { let hours = date.getHours(); let minutes = date.getMinutes(); if (hours < 10) { hours = "0" + hours; } if (minutes < 10) { minutes = "0" + minutes; } return ( '' + hours + ":" + minutes + " " ); } function getMessageSpan(jsonObj, innerMessage) { return ( '' + innerMessage + "" + "
" ); } }