You must have heard about WebSockets and Express in your tech career. WebSocket is a technology that enables real-time communication, and Express is a framework of Node Js. In this article, we will learn about web sockets with Express, why to use them, and how to implement web sockets with Express.
What is a WebSocket?
WebSocket is a kind of technology that helps us to communicate in “real-time” applications, which are fast and require less time than API (Application programming interface) protocols. Sometimes, it is referred to as a high-end computer communication protocol.
It is very helpful while requesting data and in response of date. WebSocket is needed to make the client-server communication channel.
Why use Websockets?
Websockets were invented to make real-time results effective. WebSockets initiate full-duplex, continuous communication between the client and a server. This removes unnecessary network traffic, as data can move both ways immediately through a single open connection. This helps in speed and real-time capability on the web. Websockets also help servers to keep track of clients and push the data to them as required, which is not possible in the case of using only HTTP.
Below are some usages:
WebSockets are very much used to power real-time chat apps, it also allow users to send and receive instant messages without even refreshing the page. Do not you think it is very helpful.
WebSockets can also give you real-time updates for sports scores, game events, or live betting, which allowing users to stay up to current without manually refresh the website.
It enable you real-time collaboration on documents, and also allowing multiple users to edit the same document at the same time and view each other's changes in real-time.
WebSockets can enable real-time bidding and updates during online auctions, delivering an interactive and engaging experience for participants. This can relate with any online auction for any item. So here it is very useful.
WebSockets is important for multiplayer online games, it allow real-time communication between players like you favourit game PUBG (joke), synchronising game states, and encouraging interactive gameplay.
Implementing WebSockets with Express
Now we setup the project below:
Setting up the Project
To start setting up the project, we need to have Node.js and npm installed on the system. For this, we need to create a new directory for the project and start it by running the below command.
npm init
Then, we must install Express and the required Websockets library, such as socket.io. This can be done by running the below command
npm install express socket.io
This will help in creating a package.json file and will install the required dependencies.
Creating an Express Server
After doing the above step, we need to make an express server. For this, we need to Open another document and name it server.js. Then, at that point, we should begin an Express application and make an HTTP server with the help of the createServer() method. It will be done with the HTTP module.
// The server.js code
const express = require('express');
const http = require('http');
const app = express();
const server = http.createServer(app);
Socket.io Library
Before going further we need to know how we can import socket.io.
In your terminal write below command
npm install socket.io
After that it will download the socket.io library, It will also required some of the dependencies that will directly fetched throug node_module.
Integrating Websockets
Now, for the addition of WebSockets into the Express server, we have to take the help of the socket.io library. We need to get the socket.io library with the server instance that we made.
const io = require('socket.io')(server);
Handling WebSocket Connections
Now, we can handle WebSocket connections. Here, We can use the following code to make incoming connections. It will handle the events as well.
// Server.js
io.on('connection', (socket) => {
console.log('A new client connected.');
// it will Handle incoming events
socket.on('event', (data) => {
console.log('Received:', data);
});
// it will Handle the disconnection
socket.on('disconnect', () => {
console.log('A client disconnected.');
});
});
Serving the Express App
At the end, here we have to create an Express application. Below is the code that we can use.
// Server.js
const port = 3000;
server.listen(port, () => {
console.log(`Server is listening on port ${port}`);
});
Ater compiling all the code in Server.js file run the below command.
Node Server.js
Terminal Output
Client-Side WebSocket Implementation
We want to add the client-side WebSocket connection as well. For this, we want to make an HTML file, name it index.html, and add the socket.io library. Then, we should add it with the server and handle events with the help of JavaScript.
<!DOCTYPE html>
<html>
<head>
<title>Websockets with Express - Coding Ninjas</title>
<script src="/socket.io/socket.io.js"></script>
<script>
const socket = io();
// It will Emit an event to the server
socket.emit('event', 'Hello, Server!');
// It will Handle incoming events from the server
socket.on('event', (data) => {
console.log('Received:', data);
});
</script>
</head>
<body>
<!-- You can add the HTML content here -->
</body>
</html>
Console Output
Running the Application
To run the application, we need to use the terminal to run node server.js. We should see the server running and listening on the specified port. For this, open a browser and navigate to http://localhost:3000 to load the index.html file. Now, open the developer console of the browser to view the server logs and verify the WebSocket connection.
We must also remember to handle errors and explore additional features and functionalities. We should also secure WebSocket connections offered by the socket.io library to enhance the application.
Benefits of Using WebSockets
Below are the Advantages of WebSockets:
WebSockets provide instant, bidirectional communication between the client and the server. It supports real-time updates, instant messaging, and live data streaming, resulting in a more engaged and fluid user experience.
Reduced latency: Unlike standard HTTP queries, which necessitate continuous polling or refreshing, WebSockets establish a durable connection, eliminating the need for frequent reconnection. This minimises latency and speeds up data transit between the client and server.
Scalability: WebSockets are designed to accommodate a large number of concurrent connections, making them ideal for high-scalability applications. WebSockets' persistent connection feature enables servers to manage multiple client connections efficiently and without considerable expense.
WebSockets employ a lightweight protocol that reduces the amount of data exchanged between the client and the server. This optimised data transfer minimises bandwidth consumption while improving the performance of real-time applications.
WebSockets disadvantages
Below are the disadvantages of WebSockets:
Increased server complexity: To handle WebSocket connections, manage events, and synchronise data, additional server-side code is required. This might complicate the server programming, particularly for apps that must process many WebSocket events while scaling to a high number of clients.
Limited browser support: Although WebSockets are supported by modern web browsers, older browser versions may still have compatibility concerns. You may need to build fallback techniques or alternate solutions for older browser environments if you need to support a wide range of browsers.
Stability of the network connection: WebSockets rely on a steady network connection between the client and the server. WebSocket connections can be interrupted by network disturbances or server failures, necessitating reconnection or management of disconnections on both the client and server sides.
Maintaining a large number of persistent WebSocket connections can deplete server resources like memory and computing power. To meet the rising needs of WebSocket connections, server resources must be carefully managed and scaled, especially in high-traffic applications.
Frequently Asked Questions
Does Express support WebSockets?
If we use both Websockets and Express, you should “upgrade” the HTTP server to handle Websockets. The Websocket server shares the HTTP server with Express.
Is node JS good for WebSockets?
Node. js works with real-time apps that work on push technology over the WebSocket. Node js’ two-way, real-time connections enable the freer exchange of data.
Is Kafka using WebSockets?
Kafka does not natively connect to WebSockets. Kafka and WebSockets help in scaling real-time gaming.
What is the difference between WebSocket and socket IO?
WebSocket is a technology that helps two-way real-time communication. Whereas, Socket.IO is a library that provides a layer on WebSockets which helps in making it easy to create real-time applications.
Conclusion
In this article, we have learned about WebSockets with Express and how to implement web sockets with Express. Moreover, we have seen why to use WebSockets.