Socket.io is a node package that uses web sockets for communication in Node.js applications. It provides real-time, bidirectional communication between the browser and the server.
Below is a flow diagram representing how Socket.io works in Node.js applications to handle client and server sockets for communication.
Here is an explanation for the steps in the diagram above:
When a client wants to connect to a server, it sends a web socket connection request to the server by sending a CONNECT
packet.
When the server receives the connection requests, it sends a handshake response, after which a connection is successfully established.
Now, we can send data between the client and the server. When the client wants to send data to the server, it calls the socket.emit()
function to trigger an event and sends an EVENT
packet enclosing the data.
Similarly, when the server wants to send data to the client, it calls the socket.emit()
function and also sends an EVENT
packet with the data.
The client can also request an acknowledgment from the server against the emitted event by sending an event ID in the EVENT
packet. The server responds with an ACK
packet when it receives the data.
Finally, when the client wants to end the connection to the server, it sends a DISCONNECT
packet.
As socket.io is an NPM package, we must ensure we have npm installed on our system.
We can install socket.io into our Node.js projects by simply navigating to the project directory and running the npm command:
npm install socket.io
Below are the steps we need to follow to set up Socket.io in our Node.js application.
We first open our JavaScript file that contains all the code for our server.
We create an HTTP server. We will first import the module using the following command.
const http = require('http');
We create our server using the HTTP module, as seen below.
const server = http.createServer();
After we create the server, to set up the socket. Below is the code to include the module and initialize the socket.
const socketIo = require('socket.io');const io = socketIo(server);
To handle a connection and disconnection event, we can use the following .on
functions provided by the library.
io.on('connection', (socket) => {// print msg on connectionconsole.log('A client connected.');// what to do on disconnectsocket.on('disconnect', () => {// print disconnect messageconsole.log('A client disconnected.');});});
We can also create custom socket events that can be triggered by either the server or the client. Below, we can see an example of a custom event named hello
.
// Handle custom 'hello' eventsocket.on('hello', (data) => {console.log('Received hello event:', data);});
In the function above, we pass data that we can receive from the client and append the data to a message that we print on the console.
The event can be triggered by using the .emit method. Below we can see the code to trigger the hello
event and send it Hello, server!
as its payload.
socket.emit('hello', 'Hello, server!');
Now, we will look at a sample Node.js application to see how Socket.io manages communication between a server on the back end and the client on the front end.
For this example, we will use a simple program that uses an index.html file for the client side and an index.js file for the server side.
Below we can see both files in an application. When we run the application, we can see how the client and server communicate with one another.
Click the "Run" button in the widget below to execute the application and visit the application. Please click on the link reflecting on the Your app can be found at: <link here>
in the widget below.
// import required modules const express = require('express'); const http = require('http'); const socketIO = require('socket.io'); // create the node app const app = express(); // create the server const server = http.createServer(app); // setup socketio on the server const io = socketIO(server); /// define the server port const port = 3000; // define the home route app.get('/', (req, res) => { // render the index.html file res.sendFile(__dirname + '/index.html'); }); // function that handles socket.io connections io.on('connection', (socket) => { // on connect print user connected msg console.log('A user connected.'); // on socket disconnect socket.on('disconnect', () => { // print user disconnect msg console.log('A user disconnected.'); }); // Handle custom 'hello' event socket.on('hello', (data) => { console.log('Server Received hello event:', data); // Emit a response event socket.emit('response', 'Hello, client!'); }); }); // function to listen on port server.listen(port, () => { console.log(`Server is running on Port: ${port}`); });
We will discuss this application in the context of the client-side and the server-side.
The code for the server-side communication is contained in the index.js file. Below, we can see an explanation of the code:
Lines 2–4: We import the modules that we need to include in our application, namely, express
, http
, and socket.io
.
Line 14: We define the default port (3000) for our application.
Lines 17–20: We define the home route to render the index.html file.
Lines 23–39: We define our function that handles a socket connection.
Line 25: When a user first connects and opens the web page, we display a message to the server console. A user connected
.
Lines 28–31: We define the function that handles the event where a user disconnects through time out or by closing the web page.
Line 30: Upon a user's connection termination, we print a message to the server console, A user disconnected
.
Lines 34–38: We also define a custom socket event named hello
that can be triggered by user action on the client side of the application.
Line 37: When the hello
event is triggered, the server emits a response
event with the message Hello, client
that the client handles.
The code for the client-side communication is contained in the index.html file.
Below, we can see the code explained:
Line 5: We mention the title of the application Socket.IO Hello World
.
Line 6: We include a script that fetches the Socket.IO library from the provided CDN (Content Delivery Network) URL.
Lines 7–16: We initiate a socket connection and define the socket connection events.
Lines 11–13: Here, we have created a response event for the client socket, when triggered by the server, prints a message in the browser's console along with the data it received.
Line 15: Here, we call the hello event that is processed on the server and send the custom message, Hello, server!
that is reflected in the server's console.
Free Resources