Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active November 9, 2023 03:50
Show Gist options
  • Save code-boxx/0126aa3c44bb27ab7451a3e2fa42fec3 to your computer and use it in GitHub Desktop.
Save code-boxx/0126aa3c44bb27ab7451a3e2fa42fec3 to your computer and use it in GitHub Desktop.
NodeJS Websocket Live Chat

NODEJS LIVE CHAT

https://code-boxx.com/nodejs-live-chat/

NOTES

  1. Run unpack.bat (Windows) unpack.sh (Linux/Mac). This will automatically:
    • Install the required modules npm i ws
    • Run the server - node 1-server.js, this will deploy the chat server at ws://localhost:8080
  2. Open 2-client.html in 2 different browser tabs (with file://)... Got lazy here. If you need an HTTP server, go ahead and modify 1-server.js to also serve the 2-client.html.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// (A) INIT + CREATE WEBSOCKET SERVER AT PORT 8080
var ws = require("ws"),
wss = new ws.Server({ port: 8080 }),
users = {};
// (B) ON CLIENT CONNECT
wss.on("connection", (socket, req) => {
// (B1) REGISTER CLIENT
let id = 0;
while (true) {
if (!users.hasOwnProperty(id)) { users[id] = socket; break; }
id++;
}
// (B2) DEREGISTER CLIENT ON DISCONNECT
socket.on("close", () => delete users[id]);
// (B3) FORWARD MESSAGE TO ALL ON RECEIVING MESSAGE
socket.on("message", msg => {
let message = msg.toString().replace(/(<([^>]+)>)/gi, "");
for (let u in users) { users[u].send(message); }
});
});
/* (A) WHOLE PAGE */
html, body {
margin: 0;
padding: 0;
}
* {
font-family: Arial, Helvetica, sans-serif;
font-size: 18px;
}
#chatShow, #chatForm { box-sizing: border-box; }
/* (B) CHAT HISTORY */
#chatShow { padding-bottom: 60px; }
.chatRow {
display: flex;
align-items: stretch;
padding: 5px;
border-bottom: 1px solid #eee;
}
.chatName, .chatMsg { padding: 5px; }
.chatName {
background: #025cff;
color: #fff;
margin-right:10px;
}
/* (C) CHAT FORM */
#chatForm {
display: flex;
position: fixed;
bottom: 0;
width: 100%;
height: 50px;
padding: 10px;
background: #eee;
}
#chatMsg { width: 90%; }
#chatGo { flex-grow: 1; }
<!DOCTYPE html>
<html>
<head>
<title>Live Chat Client</title>
<meta charset="utf-8">
<link rel="stylesheet" href="2-client.css">
<script src="2-client.js"></script>
</head>
<body>
<!-- (A) CHAT HISTORY -->
<div id="chatShow"></div>
<!-- (B) CHAT FORM -->
<form id="chatForm" onsubmit="return chat.send();">
<input id="chatMsg" type="text" required disabled>
<input id="chatGo" type="submit" value="Go" disabled>
</form>
</body>
</html>
var chat = {
// (A) INIT CHAT
name : null, // user's name
socket : null, // chat websocket
ewrap : null, // html chat history
emsg : null, // html chat message
ego : null, // html chat go button
init : () => {
// (A1) GET HTML ELEMENTS
chat.ewrap = document.getElementById("chatShow");
chat.emsg = document.getElementById("chatMsg");
chat.ego = document.getElementById("chatGo");
// (A2) USER'S NAME
chat.name = prompt("What is your name?", "John");
if (chat.name == null || chat.name=="") { chat.name = "Mysterious"; }
// (A3) CONNECT TO CHAT SERVER
chat.socket = new WebSocket("ws://localhost:8080");
// (A4) ON CONNECT - ANNOUNCE "I AM HERE" TO THE WORLD
chat.socket.addEventListener("open", () => {
chat.controls(1);
chat.send("Joined the chat room.");
});
// (A5) ON RECEIVE MESSAGE - DRAW IN HTML
chat.socket.addEventListener("message", evt => chat.draw(evt.data));
// (A6) ON ERROR & CONNECTION LOST
chat.socket.addEventListener("close", () => {
chat.controls();
alert("Websocket connection lost!");
});
chat.socket.addEventListener("error", err => {
chat.controls();
console.log(err);
alert("Websocket connection error!");
});
},
// (B) TOGGLE HTML CONTROLS
controls : enable => {
if (enable) {
chat.emsg.disabled = false;
chat.ego.disabled = false;
} else {
chat.emsg.disabled = true;
chat.ego.disabled = true;
}
},
// (C) SEND MESSAGE TO CHAT SERVER
send : msg => {
if (msg == undefined) {
msg = chat.emsg.value;
chat.emsg.value = "";
}
chat.socket.send(JSON.stringify({
name: chat.name,
msg: msg
}));
return false;
},
// (D) DRAW MESSAGE IN HTML
draw : msg => {
// (D1) PARSE JSON
msg = JSON.parse(msg);
console.log(msg);
// (D2) CREATE NEW ROW
let row = document.createElement("div");
row.className = "chatRow";
row.innerHTML = `<div class="chatName">${msg["name"]}</div> <div class="chatMsg">${msg["msg"]}</div>`;
chat.ewrap.appendChild(row);
// (D3) AUTO SCROLL TO BOTTOM - MAY NOT BE THE BEST...
window.scrollTo(0, document.body.scrollHeight);
}
};
window.addEventListener("DOMContentLoaded", chat.init);
call npm i ws
node 1-server.js
source "npm i ws"
node ./1-server.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment