Create a Simple Chat App in NodeJS
For this activity we'll set up a chat server and client, which is actually incredibly easy with NodeJS. The app will use 'sockets' to create connections between the server and the clients who connect to it. Don't worry about understanding any of the code at this time. The objective is to get the app up and running, not to understand the code.
Create a folder named node-chat-app and then initialize it as an NPM project by running this command in the terminal (make sure the terminal is running the command in the folder):
npm init -y
Install the socket.io package:
npm install socket.io
Create the Server
Create a file named socket-server.js in the project folder (node-chat-app), and put the following code into it. This program creates a web server that makes use of the socket.io package, which allows it to send messages to all the clients that connect to it.
const app = require('http').createServer(handler);
const fs = require('fs');
const { Server } = require("socket.io");
const io = new Server(app);
io.on('connection', (socket) => {
// When a user enters their name into the prompt on the client
// it emits an 'join' event (I made up this event name!)
socket.on("join", (username) => {
socket.username = username;
console.log(username + " has joined the chat");
io.emit("chat", "SERVER", username + " has joined the chat");
});
socket.on('disconnect', () => {
console.log('user disconnected');
});
// in the HTML page, the socket emits a 'sendchat' event
// when a user sends a message
socket.on('sendchat', (msg) => {
console.log('message: ' + msg);
io.emit('chat', socket.username, msg); // broadcast the message
//socket.broadcast.emit("chat", socket.username, msg); //this broadcasts to everyone except the person who sent the message
});
});
// to broadcast to all connected users:
//io.emit('some event', { someProperty: 'some value', otherProperty: 'other value' });
app.listen(8888);
console.log("Socket server is listening for connections...");
function handler(req, res){
fs.readFile(__dirname + '/socket-client.html', function(err, data){
if(err){
res.writeHead(500);
return res.end("Error loading socket-client.html");
}
res.writeHead(200);
res.end(data);
});
}
Create the client
Now create the client code, which will be a web page that you can load in your browser.
Create a file named socket-client.html (put it in the project folder) and add this code to it:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf8">
<title>socket client</title>
<script src="/socket.io/socket.io.js"></script>
<script>
window.addEventListener("load", () => {
const txt = document.querySelector("#data");
const btn = document.querySelector("#sendtext");
const output = document.querySelector("#output");
txt.focus();
// set up the socket connection
const socket = io.connect('http://localhost:8888');
// once the connection is made, prompt the user
// to join
socket.on("connect", function(){
const name = prompt('who are you?');
socket.emit('join', name);
});
// The server emits a 'chat' event when it broadcasts messages
socket.on('chat', function(username, data){
var p = document.createElement('p');
p.innerHTML = username + ": " + data;
output.appendChild(p);
});
btn.addEventListener('click', function(){
const text = txt.value;
if(text == ""){
return;
}
socket.emit('sendchat', text);
txt.value = "";
});
})
</script>
</head>
<body>
<div>
<input type="text" id="data" size="100"/><br>
<input type="button" id="sendtext" value="send text"/>
</div>
<div id="output"></div>
</body>
</html>
Now, start the server by entering this command in the terminal:
node socket-server.js
The server should now be up and running on port 8888.
To connect to the server, open a browser and navigate to localhost:8888/socket-client.html
You'll be prompted to connect to the server, and then you can begin chatting. Keep an eye on the terminal that's running the server and you'll see that it console logs messages.
Make sure to open another browser app (if you normally use Chrome, then try FireFox or Edge) and navigate to localhost:8888/socket-client.html. Then you can join the chat from there and send messages to and from the original browser.
For more information about web sockets, checkout this article.