Unlock the power of real-time communication with NodeJS websockets. Discover how this technology can revolutionize your development process.
Have you ever found yourself in a situation where you needed to build a real-time application? Still, you found traditional client-server communication models too slow and inefficient. If yes, WebSockets are the solution you are looking for. WebSockets is a powerful protocol that allows two-way, low-latency communication between the client and the server. According to the Stack Overflow 2022 Developer Survey , in the Web framework and technology category, Node.js came in at 47.12%. This means it is the most popular web technology.
Therefore, a question often arises: how do you use WebSockets in Node.js? Let's investigate a fundamental WebSocket application server in more detail. In this article, we'll cover the basics of WebSockets, how to configure them using Node.js, how to create a WebSocket client with JavaScript, and more. You will have a good grasp of using WebSockets with Node.js to create real-time applications by the end of this article.
What are WebSockets?
WebSocket is an Internet protocol that provides full-duplex (bidirectional) communication channels over a single TCP connection between a Web browser or other client application and a Web server. It is designed to be implemented in browsers and web servers, but can be used by any client or server application. The WebSocket protocol allows interaction between a client and a server with less overhead than half-duplex alternatives such as HTTP polling, which require additional round trips from the client to keep connections alive. In contrast, WebSockets remain open until one side explicitly closes them or due to network errors/timeouts on both sides.
WebSockets make it much easier for developers to create rich interactive applications because they no longer have to worry about creating long-running request/response cycles. Instead, they just send messages through the socket whenever necessary without making your users wait for page updates, etc., which results in better responsiveness and overall better user experience.
Furthermore, as all data transmitted over this channel is encrypted (using TLS), security concerns associated with traditional HTTP requests are drastically reduced, making them ideal for sensitive operations where privacy is most important, such as banking transactions, etc. .
WebSockets also eliminates the need to write custom code whenever an update needs to be propagated between multiple clients connected through the same session. Instead, changes made at one end automatically propagate to the others, saving valuable development resources!
Implementing WebSockets using Node.js
To implement WebSockets in Node.js, there are some prerequisites you need to have in place. It's also important that you follow security best practices when building a Node.js application. So, when it comes to ensuring the security of your Node.js applications, Node.js security best practices can help you protect your data and users.
Prerequisites
Here are the prerequisites for creating a WebSocket application:
- Node.js: You must have the latest version of Node.js installed and ready on your machine. If you don't have Node'js, you can download and install the latest version from the official Node.js website. .
- WebSocket Library: You will need to install a WebSocket library like ws to handle socket connections for your application.
Implementation
Now that we have everything configured, we are ready to start creating our WebSocket application.
Step 1: Initialize the project to run Websocket Nodejs
First, create a new Node.js project in the directory of your choice. Then install the ws library using the node package manager (npm):
mkdir nodejs-websockets cd nodejs-websockets npm init -y
Step 2: Install required dependencies
Next, we need to install the ws library, which will allow us to display client-side using an HTML page. To install the library, open your terminal and type the following npm command:
npm install ws express
This is what your package.json file looks like:
{ "name": "websockets-nodejs", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": , "author": "", "license": "ISC", "dependencies": { "express": "^4.18.2", "ws": "^8.13.0" } }
Note: This tutorial is based on ws version 8.13.0 and express package version 4.18.2. Therefore, your implementation may differ depending on the latest version during installation.
Step 3: Create a WebSocket server
Now that we have everything configured, let's create the WebSocket server for our application. First, create a new file in your project folder and name it server.js. Then add the following server-side code:
const express = require('express') const webserver = express .use((req, res) => res.sendFile('/ws-client.html', { root: __dirname }) ) .listen(3000, => console.log(`Listening on ${3000}`)) const { WebSocketServer } = require('ws') const sockserver = new WebSocketServer({ port: 2048 }) sockserver.on('connection', ws => { console.log('New client connected!') ws.send('connection established') ws.on('close', => console.log('Client has disconnected!')) ws.on('message', data => { sockserver.clients.forEach(client => { console.log(`distributing message: ${data}`) client.send(`${data}`) }) }) ws.onerror = function { console.log('websocket error') } } )
This will create a new WebSocket server on port 2048 that will listen for new connections. Therefore, when a new client connects, sends messages, or disconnects, the server will log a message to the console.
Step 4: Create a WebSocket client
To make the server available through the browser, you must then build an HTML page called ws-client.html.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>WebSocket Chat App</title> <link href = "https://cdn.jsdelivr.net/npm/ counter protected) /dist/css/bootstrap.min.css" Rel = "Stylesheet" Integrity = "Sha384-GlhTQ8IRABDZLL6O3 7cmda6J6GD "Crossorigin =" Anonymous "> <style> body{ padding:4rem; text-align: center; } </style> </head> <body> <h1>WebSocket Chat App</h1><br /><br /><br /> <form> <input type="text" placeholder="Enter message here" name="message"><br /><br /> <input type="submit" value="Send"><br /><br /> </form> <div></div> </body> </html>
Add the following code to the script element of the HTML file to build a WebSocket client:
const webSocket = new WebSocket('ws://localhost:2048/'); webSocket.onmessage = (event) => { console.log(event) document.getElementById('messages').innerHTML += 'Message from server: ' + event.data + "<br />"; }; webSocket.addEventListener("open", => { console.log("Client is now connected"); }); function sendMessage(event) { var inputMessage = document.getElementById('message') webSocket.send(inputMessage.value) inputMessage.value = "" event.preventDefault; } document.getElementById('input-form').addEventListener('submit', sendMessage);
By using port 2048 to connect to the server, this code establishes a new WebSocket client. We send a message to the server as soon as the connection is established and log a message to the console. We also keep an eye on messages from the server and log them to the console. When the client disconnects, we finally wait for the termination event to log a message.
The final HTML file should look like this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>WebSocket Chat App</title> <link href = "https://cdn.jsdelivr.net/npm/ counter protected) /dist/css/bootstrap.min.css" Rel = "Stylesheet" Integrity = "Sha384-GlhTQ8IRABDZLL6O3 7cmda6J6GD "Crossorigin =" Anonymous "> <style> body{ padding:4rem; text-align: center; } </style> </head> <body> <h1>WebSocket Chat App</h1><br /><br /><br /> <form> <input type="text" placeholder="Enter message here" name="message"><br /><br /> <input type="submit" value="Send"><br /><br /> </form> <div></div> <script> const webSocket = new WebSocket('ws://localhost:2048/'); webSocket.onmessage = (event) => { console.log(event) document.getElementById('messages').innerHTML += 'Message from server: ' + event.data + "<br />"; }; webSocket.addEventListener("open", => { console.log("Client is now connected"); }); function sendMessage(event) { var inputMessage = document.getElementById('message') webSocket.send(inputMessage.value) inputMessage.value = "" event.preventDefault; } document.getElementById('input-form').addEventListener('submit', sendMessage); </script> </body> </html>
Your HTML page would look like this.
Step 5: Start the server and run the client
Finally, start the server by running the following command in your terminal:
node server.js
You should see the following output in your terminal:
This indicates that the server is now running.
Now, go to your browser and open
The output shows that the client has successfully connected to the server.
You can see that the client application is connected to the server. Now, you can open multiple instances of the app and try to send and receive messages. As you can see, you receive a real-time response message from the server on the web page, just below the submit button.
Alternatives to the ws library
While the ws library is a popular choice for working with WebSockets in Node.js, several other libraries and frameworks can be used to achieve similar results. Let's look at some of these alternatives and compare them with the ws library.
Socket.io
Working with WebSocket connections in Node.js is simplified and intuitive by the well-known WebSocket module Soquete.io . Developers can create applications that run on a variety of devices, as this allows fallback mechanisms for browsers that do not support WebSockets.
The ability to design complicated applications with multiple communication channels thanks to Socket.io's support for namespaces and rooms is one of its key benefits. It is an excellent choice for real-time applications because it has a built-in method for handling client disconnections and reconnections.
But compared to the ws library, Socket.io has a larger code base and more dependencies, which can make it slower and use more resources. Additionally, the code is difficult to read and maintain due to the heavy reliance on callbacks.
SockJS
For browsers that do not support WebSockets, an alternative option is offered by SockJS, another WebSocket library. Additionally, it supports a variety of transports such as polling, which can be advantageous when interacting with older browsers and devices.
SockJS supports server-side implementations in many languages, including Java, Python, and Ruby, which is one of its main benefits. It is a wonderful option for developing cross-platform apps because of this.
However, SockJS is less well known and used than the ws library and Socket.io, making it more difficult to find assistance and information online. Additionally, it offers fewer features and may not be suitable for sophisticated applications.
uWebSockets.js
A lightweight WebSocket framework called uWebSockets.js provides a high-performance interface for managing WebSocket connections in Node.js. It is a good choice for high-speed data transmission applications as it uses a low-level C++ core to provide fast performance and low latency.
One of the main benefits of uWebSockets.js is its compact code base and low resource usage, which can reduce server costs and increase performance. It is a suitable option for real-time applications because it has a built-in system to handle disconnections and failures.
The learning curve of uWebSockets.js is steeper than that of other WebSocket libraries, so it may not be appropriate for novice programmers or developers with little low-level programming experience.
Pros and cons of WebSocket libraries
Each library has advantages and disadvantages depending on the application requirements and developer experience.
Here are some general pros and cons of using WebSocket libraries in Node.js.
Pros | Cons |
WebSocket libraries provide a simple and convenient interface. | WebSocket libraries can consume more resources than traditional HTTP connections. This increases server costs and reduces performance. |
They support real-time data transfers and two-way communication between clients and servers. | They can be more complicated to install and configure compared to traditional HTTP connections. |
They can create complex applications with multiple communication channels. For example. chat rooms, multiplayer games and real-time panels. | They require that both the server and client support the WebSocket protocol. This may limit compatibility with older devices and browsers. |
WebSockets Alternatives
Let's dive into alternatives to WebSockets and compare them to WebSockets.
Long Poll |
Long polling is a method where the client sends a request to the server, which keeps it open until it receives new data. As a result, real-time communication is possible without a constant connection. However, long polls have the potential to be ineffective and slow, especially for applications with many active clients. |
Server Sent Events (SSE) |
A single HTTP connection can send real-time updates from the server to the client using the SSE standard. Compared to WebSockets, SSE is easier to use and does not require a separate protocol. However, not all browsers support this. |
WebRTC |
Real-time communication is possible between browsers thanks to the WebRTC protocol. For applications like video conferencing or live streaming that need a lot of bandwidth and low latency, WebRTC is the best choice. |
MQTT |
MQTT is a lightweight messaging protocol often used for Internet of Things (IoT) applications. MQTT is suitable for low-power devices and unreliable network connections, but it is not as widely supported as WebSockets. |
It's crucial to consider your application's specific requirements when comparing WebSockets with various alternatives. WebSockets are capable of supporting multiple active clients and providing low-latency, two-way communication. Modern browsers also frequently support WebSockets, which are simple to create in Node.js using the ws package.
On the other hand, although they may be easier to build, some alternatives, such as Long Polling and SSE, may not be as effective or scalable. Although WebRTC involves additional configuration and is not always necessary, it is excellent for some use cases. MQTT works well for Internet of Things applications; however, it may not work for all real-time communication scenarios.
Conclusion
In conclusion, WebSockets are a powerful tool that can provide great solutions for building real-time applications. They enable two-way, low-latency communication between the client and server.
When used together with Node.js, they provide a scalable, high-performance solution for developers to build real-time applications with rich, interactive, and responsive GUIs without worrying about long-running request/response cycles. Additionally, WebSockets improve the security of sensitive operations such as banking transactions and eliminate the need for custom code whenever an update needs to be transferred between multiple clients.
When developing Node.js applications, it is important to find a reliable and experienced team of developers who can provide high-quality and scalable Node.js services. The Node.js development company must have prior experience in building innovative and performance-oriented Node.js applications.
If you liked this article, check out our other guides below;
- Change Node Version: A Step-by-Step Guide
- Node JS Cache: Increasing Performance and Efficiency
- Unlock the power of Node.JS microservices
- Unlocking the Power of Websocket Nodejs
- Best Text Editors and Node JS IDE for App Development