Introduction to Socket.IO and Project Setup
🎯 Introduction
User A sends User B a chat message. User B already has the chat page open—how does the server deliver the new message? Socket.IO establishes a persistent communication connection so clients can send messages and the server can notify clients. This course starts with your first connection and gradually builds a Node.js service with chat rooms, authentication, and disconnection handling.
🧱 Why Use Socket.IO?
A regular HTTP request starts at the client. The server processes it and returns a response. This works for reading articles or looking up orders. In an open chat window, however, new messages can arrive at any time. The client could make a request every few seconds, but this means querying even when nothing has changed, and a new message may have to wait until the next request.
Real-time communication lets the server push data as soon as it becomes available. Socket.IO is a library for bidirectional real-time communication. Bidirectional means either side can send data: the client to the server, and the server to the client. Real-time means delivering changes promptly, although actual latency still depends on the network and processing time.
Socket.IO has two parts. Install socket.io on the server to accept connections and handle application logic, and socket.io-client on the client to initiate connections and receive results. Clients can run in a browser or another Node.js process. This course uses Node.js clients to simulate user actions and observe server behavior directly in the terminal.
Where Can You Use It?
| Application | What the client sends | What the server pushes |
|---|---|---|
| Chat rooms | Message text and the room to join | New messages and membership changes |
| Order tracking | A subscription to a specific order | Status updates such as accepted or out for delivery |
| Collaboration tools | The current edits | Other participants' changes |
Socket.IO can use WebSocket to transport data. WebSocket is a bidirectional transport protocol; Socket.IO adds named events, broadcasting, and reconnection features. Both ends need compatible Socket.IO implementations. The browser's native WebSocket interface cannot connect directly as a Socket.IO client. Socket.IO introduction
🧰 Prepare the Environment
This course assumes no previous Socket.IO experience. The examples use JavaScript functions and Node.js modules, and explain each Socket.IO API as it appears. Node.js runs JavaScript, and npm, installed with Node.js, downloads project dependencies.
The examples use Node.js 24.19.0, socket.io 4.8.1, and socket.io-client 4.8.1. Run node -v and npm -v in your terminal to check your environment, then run the following commands one at a time.
mkdir socket-chat
cd socket-chat
npm init -y
npm install --save-exact socket.io@4.8.1 socket.io-client@4.8.1
npm init -y creates a package.json file containing the project configuration. The install command records the dependencies and their versions there. The .mjs extension tells Node.js to use import syntax without additional module configuration.
🛠 Your First Connection
Create server.mjs with the following code.
import { createServer } from 'node:http';
import { Server } from 'socket.io';
const httpServer = createServer();
const io = new Server(httpServer);
io.on('connection', (socket) => {
console.log('Client connected', socket.id);
socket.emit('welcome', 'Welcome to the chat room');
});
httpServer.listen(3000, () => {
console.log('Server started: http://localhost:3000');
});
httpServer is an HTTP server created by Node.js. new Server(httpServer) attaches Socket.IO to it, and listen(3000) starts listening on port 3000.
io.on('connection', ...) registers a connection listener. Socket.IO calls this function whenever it accepts a new client connection. connection is a built-in Socket.IO event; the client does not need to send it with emit. The socket argument represents the newly established connection, and socket.id identifies it.
By contrast, socket.emit('welcome', 'Welcome to the chat room') explicitly sends an application message. welcome is an event name we define, so our code must send it explicitly and listen for it on the client.
Create client.mjs in the same directory.
import { io } from 'socket.io-client';
const socket = io('http://localhost:3000');
socket.on('connect', () => {
console.log('Connected', socket.id);
});
socket.on('welcome', (text) => {
console.log('Server message', text);
});
socket.on('connect_error', (error) => {
console.log('Connection failed', error.message);
});
Calling io('http://localhost:3000') automatically starts connecting to that address. It creates and returns the client's socket object while starting the connection process. Establishing the connection takes time, so receiving the object does not mean the connection has succeeded yet.
The code runs through these steps:
- The client calls
io()to initiate a connection to the server. - The server accepts the connection. Socket.IO triggers the server's
connectionevent and runs our callback, which sends thewelcomemessage. - The client confirms that it has connected. Socket.IO triggers the client's
connectevent, printing “Connected”. - The client receives
welcomeand runs its listener, printing the welcome text.
The server listens for connection and the client listens for connect to learn when the connection succeeds on their respective sides. on registers what to do when an event occurs; the client's io() call initiates the connection here.
Run node server.mjs in one terminal and leave it running. Open another terminal in the same directory and run node client.mjs. The server should print a connection ID, and the client should print “Connected” and “Server message Welcome to the chat room”. Starting the server alone produces no client connection log: the callback runs only when a client connects.
❓ Questions and Answers
Q1: Why can't the client connect?
First check that the server is still running, then confirm that both sides use port 3000. If the server reports EADDRINUSE at startup, another process is using that port. When changing the port, update the client address too.
Q2: Can I create the client object and connect later?
Yes. Set autoConnect: false to disable automatic connection, then call socket.connect() when needed. Creating the object without calling connect() will not trigger a server-side connection callback for this client.
const socket = io('http://localhost:3000', {
autoConnect: false
});
socket.on('connect', () => {
console.log('Connected');
});
socket.connect();
🧪 Exercise
Start two instances of client.mjs at the same time. The server should log two connections. Each client gets a different connection ID and receives one welcome message. Press Ctrl+C in either client terminal to stop it; the other client should keep running.
🎉 You have established your first Socket.IO connection with Node.js.
