WebSocket with NodeJS – Quick Getting Started Guide

In this tutorial, we talk about WebSockets and create a NodeJS WebSocket server in under 5 minutes.

What is WebSocket?

Websocket is a simple to use, fast and tested WebSocket client and server implementation.

The Websocket specification defines an API establishing a connection between a web browser and server. WebSocket is used for creating real-time games, chat applications, displaying stock data, etc.

We have a dedicated guide about WebSocket. Which covers topics like usage of WebSockets, how to use WebSockets, what is a WebSocket client, what is a WebSocket Server, list of WebSocket API providers, how to test WebSocket servers, etc.

NodeJS and WebSocket

NodeJS is a JavaScript runtime built on Chrome’s V8 JavaScript engine. It is easy to build a WebSocket server implementation with NodeJS, keep following this tutorial and we will show you how to create a NodeJS WebSocket Server in 5 minutes.

Unlike HTTP servers, WebSockets ones don’t have any routes by default because they are unnecessary. In this protocol, you can just use a string to send and receive data from the client-side (a good practice is to send a JSON object serialized to a string).

Why should I use WebSocket?

Websocket provides us real-time updates, it is compatible with various platforms like Android, iOS, Mac, Windows, etc. Websockets help in sending multiple requests simultaneously and can also have multiple connections. We can enable proxies. And there are many open-source platforms available to help you build Websocket apps.

Building a WebSocket Server With NodeJS

As prerequisites, you should have Nodejs and NPM Installed in your system. If you don’t have it, download and install it from here: https://nodejs.org/en/download/

Once you are ready with NodeJs, open a terminal and type the following commands(For Linux or Mac Users):

For windows type the following command

This creates a directory for our shiny new WebSocket Server to be built with NodeJS.
Next, run the following command to install the ws library as a dependency

This will create a package.json file in your project and install the dependency in the node_modules directory.

After installation, create a javascript file for example “main.js” and paste the following code for creating a web server:

This code will create a basic WebSocket Server for you. The code is self-explanatory and can be edited as per your needs.

You can provide any port you want while creating the WebSocket server.

For testing it, open up a terminal and type:

Building A WebSocket Client For NodeJS Server

Keep the NodeJS program (WebSocket server) running in the terminal, and let’s create an HTML file (WebSocket client) and include the following Javascript code snippet in the file to connect to the server we just launched on our local machine.

Open up the HTML file in your browser, and you could see in the terminal that you have been connected to the WebSocket server.

When you open the HTML file, a WebSocket connection from the server is made, and you can see it in the Networks tab of your browser’s developer’s tools (right click > inspect element > click networks tab).

Check console logs in developer tools to see the messages from the WebSocket server.

The above is a very basic WebSocket client, to test your WebSocket easily, try using an online WebSocket tester like the one at PieSocket.

I hope you all have got a basic idea of how the NodeJS WebSocket works. For a more advanced tutorial on the application of WebSocket server, you should see: Create A Real-time Chat Web Application With WebSocket.

We can also use a Proxy server with WebSocket.

For using a proxy you can just paste these two lines of code in your javascript file.

Using Piesocket to Scale WebSockets

If you’re building an app that needs reliable, scalable real-time data exchange, then a third-party platform could be the answer you’re looking for. Piesocket handles all the infrastructure and hard engineering challenges for you, such as dependably scaling WebSockets, while significantly reducing the development load on your team. Piesocket enables you the freedom to build real-time applications without a Server, using C2C Communication.

PieSocket’s scalable WebSocket is surprisingly affordable and easy to use. See PieSocket’s WebSocket Documentation for more information.

Is WebSocket Secure to Use?

WebSocket is secure, so it prevents things like man-in-the-middle attacks. A secure transport prevents many attacks from the start. In conclusion, WebSockets aren’t your standard socket implementation. WebSockets are versatile, the established connection is always open, and messages can be sent and received continuously.

What Apps Can Be Made Using WebSocket

  • Chat Apps:
    A conceptually simple implementation of WebSockets; users send messages to a server, which instantly pushes these messages to the recipient. No delay! The server can also store groups of connections in channels, allowing you to message multiple people at once, or see messages from multiple people in a room, like a Slack channel.
  • Multiplayer Games:
    A common pattern for multiplayer games is to have a server store a game state that serves as the source of truth. Players will take actions or make moves that are sent to the server, which updates the game state, and pushes it out to all players. With HTTP, each player needs to regularly request the game state. With WebSockets, each move is instantly relayed to all players.
  • Collaboration Apps:
    Need to work on a shared document or canvas? You can follow the pattern above to allow multiple users to draw or type in a document and instantly update it for everyone connected.
  • Developer Tools:
    Continuous Integration tools like CircleCI use WebSockets to instantly notify you when a build has finished. Need to send your client metrics around site performance and visitor count? Open a WebSocket connection and send updates as soon as the server receives them.
  • Location-dependent apps:
    Update your server when the user’s GPS coordinates have changed, then send the user new data based on their current coordinates.

Testing a WebSocket Server

You can test WebSocket server connections by creating a Javascript connection tester as shown above or use the Online WebSocket Tester at PieSocket.

Browser Support

All current browsers are fully supported.

  • Firefox 7-9 (Old) (Protocol Version 8)
  • Firefox 10+ (Protocol Version 13)
  • Chrome 14,15 (Old) (Protocol Version 8)
  • Chrome 16+ (Protocol Version 13)
  • Internet Explorer 10+ (Protocol Version 13)
  • Safari 6+ (Protocol Version 13)

The following table compares normal HTTP connections and WebSocket connections.

WebSocket ConnectionHTTP Connection
WebSocket is a bidirectional communication protocol that can send the data from the client to the server or from the server to the client by reusing the established connection channel. The connection is kept alive until terminated by either the client or the server.The HTTP protocol is a unidirectional protocol that works on the top of TCP protocol which is a connection-oriented transport layer protocol, we can create the connection by using HTTP request methods after getting the response HTTP connection get closed.
Almost all the real-time applications like (trading, monitoring, notification) services use WebSocket to receive the data on a single communication channel.Simple RESTful application uses HTTP protocol which is stateless.
Difference between WebSocket and HTTP Connection

Hope this helps you with your journey to build a WebSocket Server in NodeJS.