Demystifying Websockets with NodeJS Part 1

Communication is the bane of life. Being a bidirectional or multi-directional concept as the case may be, it is present in every facet of human existence.

In modern web applications, we often come across real-time communication(RTC) in web apps. This simply implies sending and receiving information usually from within an application which is essential to serving its users.

Websockets are that important piece of the puzzle that helps us achieve real-time communication in software applications. Unlike regular HTTP requests, we say that the initial connection is left open thus making for swift passage of data from the server to the users, and back.

There are other approaches to real-time communication but for this piece, we would focus solely on websockets.

GETTING STARTED WITH WEBSOCKETS IN NODEJS

To integrate websockets in nodejs, we make use of the ws package made available in the npm repository.

This is after initializing our boilerplate nodejs express project.

yarn add ws

We'll also want to create an entry point javascript file to import the ws package and use the websocket server.

touch index.js

This entry file will have the following contents which initialize the websocket server and attaches it to a given port.

const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8000 });

wss.on('connection', function connection(wss) {
  wss.on('message', function message(data) {
    console.log('received: %s', data);
  });

  wss.send('Hello from the websocket world :)');
});

TESTING WITH POSTMAN

Applications using websockets are usually prefixed with ws://

For example: ws://localhost:8000

So, in Postman (PM), we navigate to My Workspace >> New >> Websocket Request >> Enter Server URL >> Connect

You should see the message below "Hello from the websocket world :)"

Awesomeness! We have scratched the surface of websockets. Now what's next?

Next, we'll go a bit further in the next part of this piece by integrating a Graphql server and adding an endpoint.

I'll see you in my next post.