Whether you are building a chat application, a video sharing app, or even a video conferencing app, Socket.io provides a connection between your clients, allowing for lightning speed data transfer between them.
It consists of both the client side and the server side, with the server side handling different connections and information dispersion. You should know that Socket.io is not a WebSocket, but rather a custom real-time transfer protocol implementation built on other real-time protocols.
This article covers the basics of Socket.io, from setting up a connection to connecting your client side to the server side.
WebSocket is a web communication protocol that allows for the transfer of data from the client side to the server side (and from the server side to the client side) once a channel between them is created. This connection persists until the channel is terminated. Unlike the HTTPS protocol, WebSocket allows for data transfer in both directions.
WebSockets can be used to build out anything from a real-time trading application to a chat application, or just about anything that requires efficient, real-time data transfer.
Sockets are connections achieved between given points in a network. A connection in a socket persists once created until it is terminated. Socket connections can be a server to the client, client to server, or between two clients or servers.
Socket.io is a JavaScript library that works similarly to WebSockets. Data transfer is done via an open connection allowing for real-time data exchange. Each connection, also known as a socket, consists of two parts: The server side and the client side. Socket.io makes use of Engine.io to achieve server-side connection with Engine.io-client for the client side.
Data transfer in Socket.io is mostly done in the form of a JSON (JavaScript Object Notation), so we will be using the JSON format for this article.
Because Socket.io needs both a server side and a client side to achieve a connection, we will be making installations for the both (server and client) starting with the server side and then moving to the client side.
Ensure that you have Node.js and node package manager (npm) already installed in your system. If not, proceed to the Node.js website to learn more about installation.
In your command line, run the following command:
npm install express Socket.io
This will install the necessary dependencies.
The next step is to set up our server. Proceed to require Socket.io, Express, and the HTTP module as shown below in your index.js file. We will be using the HTTP module to create our server instead of Express in order to pass our server to Socket.io easily:
const express = require("express"); const http = require("http"); const socketio = require("socket.io"); const app = express(); const PORT = process.env.PORT || 5000; const server = http.createServer(app); io = socketio(server); server.listen(PORT, () => { console.log(`server running at port ${PORT}`); });
As shown above, we successfully created our server. We can start our server by running the following:
node index.js
Our server should be up and running at port 5000. Notice that our server was passed to Socket.io.
For the client-side setup, let’s import the Socket.io script into our index.html file:
<script src="/socket.io/socket.io.js"></script>
Proceed to connect your client side to the server side as shown below:
=let ENDPOINT = "http://localhost:5000" let socket = io.connect(ENDPOINT); =
Alternatively, you can install socket.io-client
for your client side if you’re making use of React:
npm install socket.io-client
You can then proceed to import and create a connection like so:
import React from "react"; import io from "socket.io-client"; let ENDPOINT = "http://localhost:5000" let socket = io(ENDPOINT);
We have succeeded in setting up both our server side and client side. Now, once the client side is connected, we are notified of this connection on the server side. Socket.io helps us handle this connection as such:
io.on("connection", (socket) => { // your code snippet })
This event, equipped with a callback function, gets fired when a connection occurs.
For more complex applications, you might want to create specific rooms for different groups of users. This feature can be easily achieved using Socket.io. You can join particular rooms using the join method once a connection is achieved:
io.on("connection", (socket) => { let roomID = 2436 socket.join(roomID) })
The disconnect event is fired once a disconnection occurs:
io.on("connection", (socket) => { socket.on("disconnect", () => { }); })
Socket.io allows users to emit events and listen for them on the other end. Event emission can happen on both the server side and the client side. A “join” event, for instance, can be emitted on the client side during a connection:
socket.emit("join", { name: “peter paul”}, (err) => { if (err) { alert(err); } });
Notice that the event is emitted along with a payload in the form of a JSON, which contains the name of the user that is currently joining the connection.
Proceed to handle this event on the server side:
socket.on("join", ({ name }, callback) => { if (error) { callback(error); } else { let roomID = 2436 socket.join(roomID) console.log(name) });
You can also choose to broadcast information to everyone in a specific room during event handling:
socket.on("join", ({ name }, callback) => { if (error) { callback(error); } else { let roomID = 2436 socket.join(roomID) socket.broadcast.to(roomID).emit("adminMessage", { name: "admin", content: `${name} has joined`, }); } });
All our server-side code should look like this at this point:
const express = require("express"); const http = require("http"); const socketio = require("socket.io"); const app = express(); const PORT = process.env.PORT || 5000; const server = http.createServer(app); io = socketio(server); io.on("connection", (socket) => { socket.on("join", ({ name }, callback) => { if (error) { callback(error); } else { let roomID = 2436 socket.join(roomID) console.log(name) socket.broadcast.to(roomID).emit("adminMessage", { name: "admin", content: `${name} has joined`, }); }); socket.on("disconnect", () => { }); }) server.listen(PORT, () => { console.log(`server running at port ${PORT}`); });
The client side should be structured as such:
let ENDPOINT = "http://localhost:5000" let socket = io.connect(ENDPOINT); socket.emit("join", { name: “peter paul”}, (err) => { if (err) { alert(err); } });
Socket.io comes with a very strong utility for debugging called Debug. Prior to the introduction of Debug, Socket.io resorted to logging everything to the console, which most users found to be annoying. Later, they took a new step by not logging anything by default.
You can choose to view these messages by supplying the Debug environment variable or localStorage.debug
property when using the browser.
For the console, it is done as shown below:
DEBUG=* node yourfile.js
The *
helps you see what information is available.
For the browser it is done like so:
localStorage.debug = '*';
Socket.io, with all its simplicity, has become a top choice for developers in building applications that require real-time data transfer. With almost all modern browsers supporting WebSocket, Socket.io is poised to get even bigger.
Now that you’re equipped with knowledge on the fundamentals of Socket.io, I suggest working on a different project with the same concept as above in order to sharpen your skills and to gain a clearer understanding of the topic.
LogRocket is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowSOLID principles help us keep code flexible. In this article, we’ll examine all of those principles and their implementation using JavaScript.
JavaScript’s Date API has many limitations. Explore alternative libraries like Moment.js, date-fns, and the new Temporal API.
Explore use cases for using npm vs. npx such as long-term dependency management or temporary tasks and running packages on the fly.
Validating and auditing AI-generated code reduces code errors and ensures that code is compliant.
One Reply to "Real-time data transfer with Socket.io"
can’t able to establish a connection between server and client