Node JS WebSocket Programming Examples
What is a WebSocket?
A WebSocket is a computer communications protocol providing duplex communication channels over a single TCP connection. In other words, it allows internet-capable devices to communicate with each other, one acting as the client and the other acting as the server, with both able to initiate communication.
What types of applications use WebSockets?
The WebSocket protocol is used wherever a solution requires real-time communication and example use cases include:
WebSockets create a TCP socket connection between multiple devices or processes. As will be discussed later, similar functionality can be implemented using HTTP Long Polling or a hosted pub/sub service, but let’s build a simple example first using WebSockets and Node.js.
Talk to an Expert
Let's connect to discuss your real-time project.
Is Node.js good for WebSockets?
Yes, Node.js is a great choice for implementing websockets as it provides a fast and scalable server-side environment that supports the popular ws library.
Why we use Node.js for WebSockets?
WebSockets require a persistent connection between the client and the server, which means that the server needs to be able to handle a large number of concurrent connections. Node.js uses an event-driven, non-blocking I/O model which makes it well suited to handle the resource requirements of WebSocket-based applications.
How to implement WebSockets in Node.js
The following guide will walk you through creating a WebSocket server in Node.js and show how you can connect to it using a WebSocket client running in the browser.
How many WebSocket connections can a Node.js server handle?
Production applications might handle tens of thousands of WebSocket connections simultaneously but the exact number will depend on several factors such as server hardware resources, the network bandwidth and the complexity of the application logic.
Node.js WebSocket API Example - a basic chat application
All source code associated with this blog is hosted on GitHub
To build a basic chat application with WebSockets, you will need both a client and server component.
For the server, we will use Node.js, and the client-side code will run within a web browser such as Chrome.
Node.js WebSockets Code (Server)
This application will require both a web server (HTTP server) and a WebSocket server (wss). The web server allows us to load our client (running in a browser), and the WebSocket server handles the bidirectional chat messages.
How to create a websocket server in NodeJS?
The web server portion will serve a single web page to the client, websocket-client.html, on port 3000:
A WebSocket server can be created in only a few lines using the Node.js WebSocket library (ws) package:
Writing Websocket events for NodeJS examples
After creating an instance of a WebSocket server and specifying the port to run on, we can define any action that should happen after the WebSocket connection is established. In our case, we write connection events to the console and forward any messages we receive to previously connected clients. WebSockets are designed to run on the same ports as HTTP/HTTPS (i.e., 80 and 443).
And with that, the server portion is complete. Every time a message is received on any socket, it proxies the message to every connected client, which is the basis of any group-chat app.
The full index.js code looks like this:
And you can run it from the command line as follows:
Messages can either be text or JSON encoded (JSON.stringify). This code uses the utf-8 charset by default.
WebSockets code example (client / browser)
We don’t have to install additional software or packages to use WebSockets with modern web browsers. Create a listening WebSocket by providing a correctly formatted URI:
And defining an event handler for when a message is received from the server:
That’s it. We can now receive data from the WebSocket server.
To send a message event from the client, you send() on the socket object:
To make our chat app functional, we just need to add an input field and a ‘send message’ button, so your frontend HTML code should look something like this (styling & css omitted for brevity):
Make sure you name your HTML page “websocket-client.html” and launch a few tabs in your browser, navigating to http://localhost:3000. You should see messages received in every tab:
Creating the same chat app without a Node.js server
If you don’t have a server or have concerns about scaling your server infrastructure to meet your application’s future demands, you should opt for a hosted real-time communication solution such as Socket.io or PubNub.
PubNub is a globally distributed and scalable cloud platform, so you do not have to worry about deploying and maintaining servers on your backend. PubNub SDKs can identify users and send messages to specific channels, which only subscribed users will receive.
So, how would the simple chat app presented above be written with PubNub? One benefit of PubNub is that it is protocol agnostic. PubNub uses the ‘publish’ and ‘subscribe’ architecture (pub/sub) to send and receive bidirectional messages.
To subscribe for incoming messages, create a PubNub instance, define the channel, and add a listener:
The page will be updated whenever messages are received on the ‘ws-channel’. The code above uses ‘demo’ keys, but you can obtain your custom PubNub keys for free.
To send messages over PubNub, publish on the same channel you subscribed to previously, in this case:
The channel model is very flexible and extensible, but for this simple example, it is sufficient to just send and receive messages on the same channel. Your message will be delivered anywhere in the world in under 100ms.
Since there is no server component required with a PubNub deployment, the entire application, written in HTML and JS, is contained within a single file:
You can see a live version of this code at
And that’s all there is to it! For more information on developing with PubNub, check out their range of tutorials and demos. Alternatively, check out the PubNub interactive live tour to understand how the platform provides real-time interactivity to applications.