Introduction to Socket.IO Library
The JavaScript package Socket.IO allows Node.js to establish persistent socket connections for real-time, bidirectional, event-based communication between clients (typically web browsers) and servers. In contrast to the conventional HTTP request/response approach, which provides a long-lived, open channel of communication, Socket.IO enables the server to proactively send messages to clients and vice-versa, in contrast to the server’s passive reaction to client requests. For applications that need to send messages often, such chat apps, live analytics, multiplayer games, and collaborative editing tools, this makes it a great option.
Providing an emulation layer for browsers that do not natively support WebSockets is one of Socket.IO’s main advantages. While WebSockets are a contemporary standard for full-duplex communication over a single TCP connection, Socket.IO ensures wide compatibility across all browsers by seamlessly reverting to older methods, such as long-polling, to mimic this persistent connection. It is divided into two components: a client-side component that operates in the browser and a server-side component that runs on Node.js.
What are WebSockets?
The server can proactively transmit messages to the client without the client making a specific request thanks to WebSockets, in contrast to HTTP, which uses a passive server architecture in which the client makes a request and waits for a response. Communication between the client and the server is possible at the same time. This makes WebSockets perfect for applications that need to exchange data continuously and in real time, including chat programs, online multiplayer games, editing tools for collaboration, or live data feeds. The little data overhead needed to transmit messages is another factor that makes this communication low-latency.
Modern web browsers broadly support WebSockets. For secure connections, the wss://
protocol is used, which is the secure, encrypted version of ws://
, similar to https://
for HTTP.
Installation
It is simple to install Socket.IO using the Node Package Manager (npm). Make sure that Node.js and npm
are installed on your computer first.
Open the command line, navigate to the project directory, and type the following to install Socket.IO:
npm install socket.io
Socket.IO is installed by this command into the node_modules
directory of your project and saved as a dependency in your package.json
file.
“Hello World!” with Express Server
Let’s configure an Express server and Socket.IO to create a simple “Hello World!” application. In order to deliver a basic message from the server to the client, this example will show how to connect.
Server-side Setup (Node.js with Express and Socket.IO)
If it hasn’t been done earlier, you must first install Express as well:
npm install express
Create a file named server.js
(or app.js
) in your project directory and add the following code:
// Import the Express module and Socket.IO
const express = require('express');
const app = express(); // Creates an Express application
const server = require('http').Server(app); // Create an HTTP server using the Express app
const io = require('socket.io')(server); // Connect Socket.IO to the HTTP server
// Define the port number
const port = 3000;
// Serve static files from the 'public' directory
app.use(express.static(__dirname + '/public'));
// Listen for new connections to Socket.IO
io.on('connection', (socket) => { // This callback function is executed upon every new client connection
console.log("New WebSocket connection!"); // Log when a client connects
// Send a message from the server to the client immediately upon connection
socket.emit('message-from-server-to-client', 'Hello World from Server!'); // Send event to the specific client
// Listen for messages from the client
socket.on('message-from-client-to-server', (msg) => { // Listen for 'message-from-client-to-server' event
console.log(`Received message from client: ${msg}`); // Log the message received from the client
});
});
// Start the server and listen on the specified port
server.listen(port, () => { // Make the app listen on the defined port
console.log(`Socket.io Hello World server started on http://localhost:${port}`); // Log server start message
});
To run the server, open your terminal, navigate to the directory where you saved server.js
, and execute:
node server.js
Expected Server Output:
Socket.io Hello World server started on http://localhost:3000
New WebSocket connection!
Received message from client: Hello World from Client!
Client-side Setup (HTML and JavaScript)
Socket.IO automatically serves its client-side library from /socket.io/socket.io.js
. Create a public
directory in your project root, and inside it, create an index.html
file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Hello World with Socket.io</title>
<!-- Include the Socket.IO client-side library -->
<script src="/socket.io/socket.io.js"></script> <!-- -->
</head>
<body>
<h1>Socket.io Hello World Client</h1>
<p id="message-display">Waiting for server message...</p>
<script>
// Connect to the Socket.IO server
const socket = io("http://localhost:3000");
// Listen for messages from the server
socket.on("message-from-server-to-client", function(msg) { // Listen for 'message-from-server-to-client' event
document.getElementById('message-display').innerHTML = msg; // Display the message on the page
console.log("Received from server: " + msg); // Log the message to console
});
// Send a message from the client to the server after a short delay
setTimeout(() => {
socket.emit('message-from-client-to-server', 'Hello World from Client!'); // Send 'message-from-client-to-server' event
}, 1000); // 1-second delay
</script>
</body>
</html>
Open your web browser and navigate to http://localhost:3000
.
Expected Browser Output:
- The page will initially show “Waiting for server message…”
- After a brief moment, it will update to “Hello World from Server!”
- In your browser’s developer console, you will see:
Received from server: Hello World from Server!
This setup demonstrates a basic bidirectional communication: the server sends a message to the client upon connection, and the client sends a message back to the server after a short delay. The server’s console will confirm receiving the client’s message.