Rabikant
Posted on March 9th
How To Build a Websocket Client in Node
"Let's Learn How To Build a Websocket Client in Node"
What is WebSocket?
WebSockets have become the basis for a new era of web applications, considering that full-duplex communication between the client and server has become possible with real-time efficiency. WebSockets have become significant for various today’s web applications, starting with live chat software and ending with online gaming applications or financial market indicators.
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 unnecesWhy Use PieSocket?sary. 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.
What is a WebSocket Client?
A WebSocket client is an application that establishes and maintains a connection to a WebSocket server. This client listens for messages, sends data to the server, and responds to connection events like opening, closing, or encountering errors. WebSocket clients are commonly used in chat applications, stock market dashboards, live notifications, and multiplayer gaming platforms.
In this tutorial, we will:
- Set up a WebSocket client in Node.js.
- Connect it to a WebSocket server using a wss:// URL.
- Use PieSocket’s WebSocket service for easy connectivity.
- Explain each part of the code in detail.
Installing Dependencies
Before we start coding, we need to install the required dependencies. The ws package is a widely used WebSocket implementation for Node.js. Run the following command to install it:
npm install ws
This will add the ws package to your project, which will allow us to create a WebSocket client.
Importing the WebSocket Module
const WebSocket = require('ws');
Here, we are importing the ws module, which allows us to create a WebSocket client in Node.js.
Defining the WebSocket Server URL
const wsUrl = "wss://free3.piesocket.com/v3/your_channel_id?api_key=your_api_key";
We specify the WebSocket server URL. In this case, we are using a PieSocket WebSocket server. If you have your own WebSocket server, replace this URL with the appropriate one. You can also use ws://echo.websocket.in, its a free echo server provided by PieSocket.
Creating a WebSocket Client Connection
const ws = new WebSocket(wsUrl);
This line establishes a connection to the WebSocket server.
Handling the open Event
ws.on("open", () => {
console.log("Connected to WebSocket server");
ws.send("Hello from Node.js WebSocket client!");
});
The open event is triggered when the connection to the WebSocket server is successfully established. Once connected, we send a message to the server ("Hello from Node.js WebSocket client!").
Handling Incoming Messages
ws.on("message", (message) => {
console.log(`Received: ${message}`);
});
Whenever the WebSocket server sends a message, this event is triggered, and we log the received message.
Handling Errors
ws.on("error", (error) => {
console.error(`WebSocket error: ${error.message}`);
});
If there is an error in the connection, this event logs the error message.
Handling Connection Closure
ws.on("close", () => {
console.log("Disconnected from WebSocket server");
});
When the WebSocket server disconnects, this event logs that the connection has been closed.
Running the WebSocket Client
Once we have written the code, we can run our WebSocket client using the following command:
node client.js
If the connection is successful, you should see the following output:
Connected to WebSocket server
Received: Welcome to PieSocket WebSocket server
Why Use PieSocket?
PieSocket is a cloud-based WebSocket provider that allows you to set up WebSocket connections without managing your own server infrastructure. It offers features such as:
- Scalability – Handles large volumes of real-time data.
- Security – End-to-end encryption.
- Reliability – Automatic reconnection and load balancing.
If you don’t have your own WebSocket server, PieSocket is a great alternative.
Key Benefits of WebSockets
WebSockets offer several advantages over traditional HTTP connections:
Real time Communication – The capability of sending and receiving messages at one go without having to poll. Low Latency – Faster interaction compared with HTTP. Lower Bandwidth – No additional HTTP request. Persistent Connection – A connection created by WebSocket persists throughout the session.
All these features make WebSockets suitable for real time apps like chat applications, real time notifications, collaborative editing, online games etc.
Conclusion
In this tutorial we learned how to implement WebSocket client in Node.js with the help of package called ‘ws’. The whole implementation was discussed along with dependencies and connection to WebSocket server — PieSocket.
When you use WebSockets into your Node.js apps, you can establish faster and real time communication applications. WebSockets work well for all applications irrespective of whether you are working on a chat application, live stock ticker, or collaboration tools.
Complete Code
The project is available on our GitHub : https://github.com/piehostHQ/node_ws_client
