Real-time chat app using WebSockets and Nodejs

Rabindra Joshi
8 min readFeb 13, 2018

--

Welcome to your very first WebSocket tutorial. This is the first part of the WebSockets chat app series.

What are WebSockets?
They’re a way to communicate between a client the browser and a server and this communication is bi-directional. That means that data can flow in both ways, we can flow from the client to the server and also from the server to the client. Because these Web Sockets are always open it allows for real-time data flow in our application.

This is all really cool but what does it mean in a real-world example?
I want you to imagine we have this kind of chat application which is hosted on the server right here so all these different clients are different people around the world in their browser and they all go to particular URL to request this chat application in their browser.

Now all users are viewing it in the browser, one person John over there types something into this chat and click send then that message is going to instantaneously be updated in all of these different clients around the world that are viewing that chat.

This is WebSockets in action but what’s going?
When we first request the chat application in the browser we get that chat application and at the same time we’re opening up this WebSocket between the client and the server so now we have all of these different clients from different browsers around the world which all have their own WebSocket connection to the server. This means that data can flow back and forth between it in real time because these are always open.
When John creates a message and clicks send we’re sending that message down this WebSocket to the server the server receives it and then says hey this is a chat message and what to do with that? I’m going to send it down all these other web sockets which connecting to these clients to each individual clients so that they can see that updating message in their chat.

The message is going to send up the WebSocket to the server then the server sends it down each individual web socket to all the remaining clients and that’s why they see this message okay instantaneously.
I want you to take note here this data transfer is occurring in real time and we’re not using any kind of Ajax request from each of these different clients to request any new data from the server it’s all happening without the client having to make any additional requests at all.
There’s tons of different uses for WebSockets not just chat rooms and they include making multiplayer browser games collaborative code editing software some kind of live text for sports on news websites online drawing canvases real time to do apps etc.

In this tutorial we are going to make a simple chat application that works something like this:
We have it open in two different browsers on a same server. Instead of these two browsers on same computer this could be two different computers in two different parts of the world because it works exactly the same way, both are connecting to the same server and the getting this chat application back in their window.
We have an input for a handle, that’s your name. I’ll just say Mary and I’m doing the other one as a John We also have an input for the message so I can type a chat. When John is typing, Mary is getting John is typing a message over in the other client. When I click send then we get the updated message on both the clients.

We’re using WebSockets to send that data to the server the server then sends it down to this client and shows it in real time and we’ve not made any kind of requests from this client to the server at all. It’s just open and listening through this WebSocket and receiving data.
That’s what we’re going to do in this set of tutorials.
Before you start this series you must have nodejs installed.
If you haven’t download from https://nodejs.org/en/. It comes with npm, which is the package manager for node.

To check whether you have node installed on your computer just open your command line tool.
The commanded to type is node -v. If you've got it installed it's going to show the version number right there otherwise you want to make sure you have node installed.

λ node -v
v9.5.0
λ npm -v
5.6.0

I’m going to provide all of the course files for this series they can be found on my github repository here called frost-chat . Link will also be available at the end of each tutorial.
We’re going to create a very simple Express app on node to use WebSockets with. We’re going to use WebSockets to communicate between the client, the browser, and the server. We’re going to use the socket.io library. To do that we’re going to need some kind of server-side code. Now I’m going to run that on node.js so we’re going to create a simple Express app on nodeJS. This is not going to be an extensive Express tutorial if you want to learn more about those, explore other tutorials on this site. I’m going to move quite swiftly and create this Express application. The first thing I want to do is initialize this project so I’m going to come to my command-line tool make sure I’m in the correct directory and then npm init.

λ npm initpackage name: (frost-chat)                                   
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author:
license: (ISC)
About to write to F:\frost-chat\package.json: {
"name": "frost-chat",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
Is this ok? (yes)

Now we’ve initialized this project and created this package JSON file forms which is going to list information about our project and also list our dependencies when we install them.
Speaking of dependencies, we need express for our app.

λ npm istall express --save

Once installed you’re going to notice two things first of all in our package JSON file you’ll see the dependencies property and it lists express as a dependency so it’s keeping track of that. Second, you’ll see this node modules for that appear that’s got everything inside that it needs to run the app. You don’t need to edit that or do anything with it at all.

The second one is going to be called nodemon and this is more of a convenience than a necessity we don’t need it. I’m going to install it for convenience. It looks out for changes that we make to our server-side code and then restarts the server for us when it needs to a rather than having us manually restart the server.
I’m gonna save it to our dependencies this time to our dev dependencies because this is not a necessity of the application just a convenience.

npm install nodemon --save-dev

Now we can see that listed in our dev dependencies in the package.json.

.......................
"devDependencies": {
"nodemon": "^1.14.12"
}
.....................

When we start in the server with nodemon we just need to type nodemon index just once. We'll do that later.

We’ve installed those packages we can start creating this application so we need that entry file and that is index.js. Let's create that new file index.js and the first thing we want to do in here is require Express since we're making it an Express app so open the file index.js and type:

var express = require(“express”);

Node is going to be clever enough to look in this node modules for the for express require in this file. The next thing we want to do is set up our app. Underneath express, what we want to do is create a variable called app and then set it to express, that’s this thing we just require here this is actually a function we’re requiring and we want to invoke that function.

var app = express();

We also want to create a server and I’m going to store this in a variable so we can use it later on when we start working with socket.io it’s going to make things easier for us.I’m going to store this in a variable app and then listen to a specific port number right. When we go to a localhost then the port number in our browser is going to listen to requests on this port number. You can type in whatever port number you want in. I'm going to type in 9090 and we're going to listen to this port number. When it starts listening to this port number we can fire back a callback function just to let us know and it's listening for requests on this port number. Let's say console.log and we'll say something like listening to requests on port 9090.

var server = app.listen(9090, function () {
console.log("Listening on port 9090");
});

Now run this app by nodemon index and you get the message

Listening on port 9090

But when I go to port 9090 on localhost nothing is going to happen and it says

We actually want to serve something to the browser. To do that we’re going to use some middleware to serve some public or static files.

app.use(express.static("public"));

The public folder will be used as the static folder for our express app.

Let’s serve an index.html from the public folder.

  1. Create public folder.
  2. Create index.html in public folder.

Here’s the content of index.html:

<!doctype html>
<html lang="en">
<head>
<title>Frost Chat: WebSockets</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>

Let’s quickly add a css file too.

Link it in the html file with

<link rel="stylesheet" href="/styles.css">

I’ll add some content to css file, and since this is not a css tutorial I won’t be explaining much about it.
We’ll start working with WebSockets in the next tutorial.
Visit the GitHub repo here.
Current Progress here.

Put your questions in the comment section.
You can find me on Twitter and Facebook.

Read second part here.

--

--