Getting Started with Socket.IO: Building Real-Time Web Applications

Jitendra Kumar
Engineering @ Housing/Proptiger/Makaan
4 min readJun 12, 2024

What is Socket.io ?

Socket.IO is a server-side library for nodejs that enables low-latency, bidirectional and event-based communication between a client and a server using client-server architecture while it is a wrapper around WebSockets For Node.js, it is super easy and simple to use especially when dealing with chat messages or Real-time data.

Socket Client-Server Architecture

How persistent bi-directional connection is established between client(s) and server ?

The connection process between a Socket.IO client and server involves several steps. Below is a detailed breakdown of the key steps:

1. Handshake Initialization:

  • The client initiates a connection to the Socket.IO server by sending an HTTP request (often a GET request) to the server using constructor provided by socket-io.client library.
// Connect to the server (URL is optional if both client and server are at same origin )
const socket = io('http://localhost:3000');
  • The request includes a specific path, typically /socket.io/, and it may also include query parameters indicating the supported Socket.IO protocol version (EIO=3), transports, and other details.
  • Example : GET /socket.io/?EIO=3&transport=polling&t=timestamp

2. Server Handshake Response:

  • The Socket.IO server receives the initial HTTP request and responds with a handshake.
  • The response includes the selected transport mechanism and a unique session ID (sid) that will be used to identify the connection.

3. Connection Upgrade (Optional):

  • If the client and server both support WebSocket and agree to use it, they may negotiate to upgrade the connection from HTTP to WebSocket. This is an optimization for more efficient and bidirectional communication.

4. Transport Initialization:

  • Based on the handshake response, the client initializes the chosen transport (e.g., WebSocket, polling).
  • If using WebSocket, a WebSocket connection is established directly.
  • If using polling, the client may start polling the server for updates.

5. Real-Time Communication:

  • Once the transport is established, the client and server can engage in real-time bidirectional communication.
  • Messages can be sent from the client to the server and vice versa.

6. Heartbeat and Keep-Alive:

  • Socket.IO includes a heartbeat mechanism to ensure that the connection remains alive.
  • The client periodically sends a heartbeat signal to the server to indicate that it is still connected.
  • The server responds with a heartbeat acknowledgment.

Socket.io Events and how it works ?

Key Concepts :

  1. Events: Events are the fundamental mechanism for communication in Socket.IO. Both the client and server can emit and listen for events.
  2. Namespaces: Namespaces provide a way to create separate communication channels within a single Socket.IO connection. The default namespace is /.
  3. Rooms: Rooms are subsets within a namespace that clients can join or leave. They are used for grouping sockets and broadcasting messages to multiple clients within the same namespace.

Once the connection is established between client(s) and server, communication can begin using the following mechanisms.

  1. Event Emission: Once connected, both the client and server can emit events to each other. These events can carry data, which is passed as arguments to the event handlers.
  2. Event Handling: Both client and server can listen for specific events and execute corresponding callback functions when these events are received.

You now have a good understanding of the basics of Socket.IO, so let’s move on to the implementation.

  1. Ensure Node.js is installed on your system.
  2. Install the Socket.IO client library with npm install socket.io-client.
  3. Create a directory named public in your project folder, and then create a client.js file inside the public directory. Additionally, create an index.html file to include the client-side code.
// Connect to the server
const socket = io('http://localhost:3000');

// Listen for connection event
socket.on('connect', () => {
console.log('Connected to the server');

// Emit a custom event to the server
socket.emit('customEvent', { someData: 'hello' });
});

// Listen for a custom event from the server
socket.on('responseEvent', (data) => {
console.log('Message from server:', data);
});

// Handle disconnection
socket.on('disconnect', () => {
console.log('Disconnected from the server');
});

4. Add the following code in index.html file

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Socket.IO with Express</title>
</head>
<body>
<h1>Socket.IO with Express</h1>
<script src="/socket.io/socket.io.js"></script>
<script src="client.js"></script>
</body>
</html>

5. Install the necessary dependencies for server : npm install express socket.io

6. Create a server-side JavaScript file named server.js.

const express = require('express');
const http = require('http');
const socketIo = require('socket.io');

// Initialize Express app
const app = express();
const server = http.createServer(app);
const io = socketIo(server);

// Serve static files from the public directory
app.use(express.static('public'));

// Handle socket connection
io.on('connection', (socket) => {
console.log('A client connected');

// Listen for a custom event from the client
socket.on('customEvent', (data) => {
console.log('Received customEvent:', data);

// Emit an event to the client
socket.emit('responseEvent', { message: 'Hello from server' });
});

// Handle client disconnection
socket.on('disconnect', () => {
console.log('A client disconnected');
});
});

// Start the server
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});

7. Start your server by running node server.js command in your project directory

8. Please open your browser and navigate to http://localhost:3000. You will see messages in the console, as we have not integrated a user interface yet (assuming you can handle that part). To test with multiple clients, open http://localhost:3000 in multiple tabs.

This setup allows you to serve an HTML page with client-side JavaScript that connects to the Socket.IO server, facilitating real-time communication.

Conclusion : Socket.IO provides the tools and flexibility needed to create responsive and dynamic user experiences. By leveraging Socket.IO in your projects, you can deliver real-time functionality with ease, enhancing user engagement and interactivity.

Hope you liked the blog! Please give it a thumbs up. 👍

--

--