WebSockets Tutorial: Creating a real-time WebSocket Server

Johnny Simpson
JavaScript in Plain English
4 min readMay 24, 2021

--

Photo by Skylar Kang from Pexels

A lot of the work we do with JavaScript involves us sending information back and forth from servers. You are probably familiar with the concept of APIs, which send data to servers or websites in a particular format, to get a specific response back.

These are known as REST APIs. Although useful, they are not very good at constant streams of data. If you try to do something real-time with REST APIs, you’re going to have a bad time. Fortunately, if we want a real-time connection with a user, we have an alternative, known as WebSockets.

How WebSockets work

Websockets are essentially constant connections made between the server and your computer. When you access a website, it can send a GET request to the server, to initiate a WebSocket connection between the user and the server.

WebSockets vs REST API

If the user leaves the website, the connection is cut, so the user only has access to the WebSocket as long as they continue to use the website.

How long can a WebSocket stay open?

Once a WebSocket is created, it can theoretically stay open forever. There are a few exceptions to this:

  • The server goes down — this will break the WebSocket, but we can attempt to reconnect to it.
  • A power outage or internet connection problem — the connection will break if the user’s internet stops.
  • Inactivity — if the user doesn’t interact or send data through the WebSocket, the connection inevitably times out.

As such, when we design our WebSockets, we need to consider how we reconnect to them if the user’s connection stops for some reason, as to not interrupt the user’s experience.

Making a WebSocket

A WebSocket, therefore, consists of two parts — the server, and the local machine that the user is using. For what we are doing, we’ll be using Node.js as our server, but other languages also support WebSockets.

When the user accesses our website, we load a file with some JavaScript that contains a connection string to our WebSocket. Meanwhile, in our backend, we will have WebSocket set up that the user will connect to. This is shown in the below diagram:

Step 1: Creating our Server #

Let’s start by making our Node.js web server for the WebSocket connection. For this, we’re going to be using an express server with an additional package called express-ws. This additional package will allow us to use ws in the same way we might use get.

The last clause, app.ws, refers to the WebSocket, and that's what we'll try to connect to on the frontend. For the time being, the WebSocket only console logs a message, whenever it receives one from the frontend. Let's change that so it sends something back:

Now, whenever this WebSocket connection receives data, it will send back an object, which we’ve defined above. We can then manipulate this object in our frontend, to display or change views for the user.

Step 2: Connect on Frontend

As we mentioned before, when our user visits our website, we provide them with some local JavaScript in our HTML document. I’ve added a few other elements for our demo in the index.html file:

Next, we need to put some connection details in our local.js file. I have created a single connection file which we run after the document has loaded. It looks like this:

To connect to a WebSocket, we have to use ws://, instead of HTTP, and wss://, instead of HTTPS. We put that into our new WebSocket() function to generate our connection. Inside our connection function, we then have three event listeners:

  • socket.onopen - if the connection is successful and open, this fires.
  • socket.onmessage - any time the server sends a message to us, this fires. In our example, we will append a new element to our user's HTML if they receive data which has append set to true.
  • socket.onerror - if the connection fails, or an error occurs, this will fire.

Let’s tie it all together — since we are storing our socket variable in the global scope, we can send data after the connection is successful. The below event listener connects to the WebSocket, and then sends data to the server when the user clicks our HTML button.

When the server receives this data, it then sends back its own data, as the server's message’ event fires. This comes back to the user, which then adds a new element to their document.

Conclusion

And that’s it! Now we have a functioning WebSocket, which allows you to send data to the server, and back to the user. If you want to learn more or download the source code, here are some useful links:

More content at plainenglish.io

--

--