Tiếng Việt

Introduction about SocketIO



Chat applications such as Messenger, Zalo, Telegram, … have been an indispensable part for most people in today's life. Unlike other applications that are only updated (refreshed) when “Reloading” the page, chat application is a real-time application, it needs to be updated (refreshed) quickly whenever possible. have someone interact with the chat room (data changes). In this blog post, I introduce the Socket.IO library - one of the popular libraries used to write chat applications like the one above.

What is Socket.IO ?


Socket.IO is a library that enables low-latency, bidirectional and event-based communication between a client and a server.It is built on top of the WebSocket protocol and provides additional guarantees like fallback to HTTP long-polling or automatic reconnection.

Socket.IO is NOT a WebSocket implementation. Although Socket.IO indeed uses WebSocket for transport when possible, it adds additional metadata to each packet. That is why a WebSocket client will not be able to successfully connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a plain WebSocket server either.


HTTP long-polling fallback

The connection will fall back to HTTP long-polling in case the WebSocket connection cannot be established.

Automatic reconnection

Under some particular conditions, the WebSocket connection between the server and the client can be interrupted with both sides being unaware of the broken state of the link.That's why Socket.IO includes a heartbeat mechanism, which periodically checks the status of the connection.And when the client eventually gets disconnected, it automatically reconnects with an exponential back-off delay, in order not to overwhelm the server.

Packet buffering

By default, any event emitted while the Socket is not connected will be buffered until reconnection. While useful in most cases (when the reconnection delay is short), it could result in a huge spike of events when the connection is restored. There are several solutions to prevent this behavior, depending on your use case: use the connected attribute of the Socket instance

if (socket.connected) {
          socket.emit(/* ... */);
          socket.emit(/* ... */);
} else {
          // …

use volatile events

socket.volatile.emit(/* ... */);


Socket.IO provides a convenient way to send an event and receive a response.. Sender:

socket.emit("hello", "world", (response) => {
     console.log(response); // "got it"


socket.on("hello", (arg, callback) => {
    console.log(arg); // "world"
    callback("got it");

Bạn cũng có thể thêm thời gian chờ:

socket.timeout(5000).emit("hello", "world", (err, response) => {
  if (err) {
    // the other side did not acknowledge the event in the given delay
  } else {
    console.log(response); // "got it"


On the server-side, you can send an event to all connected clients or to a subset of clients.

// to all connected clients
// to all connected clients in the "abc" room


Namespace cho phép bạn phân chia logic của ứng dụng của mình qua một kết nối được chia sẻ duy nhất. Điều này có thể hữu ích, chẳng hạn như nếu bạn muốn tạo kênh "quản trị viên" mà chỉ những người dùng được ủy quyền mới có thể tham gia. IntroductionAboutSocketIO2.png

io.on("connection", (socket) => {
  // classic users
io.of("/admin").on("connection", (socket) => {
  // admin users


Emitting events

The Socket.IO API is inspired from the Node.js EventEmitter, which means you can emit events on one side and register listeners on the other. Server

io.on("connection", (socket) => {
  socket.emit("hello", "world");


socket.on("hello", (arg) => {
  console.log(arg); // world

You can send any number of arguments, and all serializable datastructures are supported, including binary objects like Buffer or TypedArray. Server

io.on("connection", (socket) => {
  socket.emit("hello", 1, "2", { 3: "4", 5: Buffer.from([6]) });


socket.on("hello", (arg1, arg2, arg3) => {
  console.log(arg1); // 1
  console.log(arg2); // "2"
  console.log(arg3); // { 3: '4', 5: ArrayBuffer (1) [ 6 ] }

Listening to events

socket.on(eventName, listener): Adds the listener function to the end of the listeners array for the event named eventName.

socket.on("details", (...args) => {
  // ...

socket.once(eventName, listener): Adds a one-time listener function for the event named eventName.

socket.once("details", (...args) => {
  // ...

socket.off(eventName, listener): Removes the specified listener from the listener array for the event named eventName.

const listener = (...args) => {

socket.on("details", listener);

// and then later...
socket.off("details", listener);

socket.removeAllListeners ([eventName]): Removes all listeners, or those of the specified eventName.

// for a specific event
// for all events


A room is an arbitrary channel that sockets can join and leave. It can be used to broadcast events to a subset of clients. Each Socket in Socket.IO is identified by a random, unguessable, unique identifier Socket#id. For your convenience, each socket automatically joins a room identified by its own id. Please note that rooms are a server-only concept (i.e. the client does not have access to the list of rooms it has joined).


You can call join to subscribe the socket to a given channel.

io.on("connection", (socket) => {
  socket.join("some room");

And then simply use to or in (they are the same) when broadcasting or emitting.

io.to("some room").emit("some event");

You can emit to several rooms at the same time.

io.to("room1").to("room2").to("room3").emit("some event");

In that case, a union is performed: every socket that is at least in one of the rooms will get the event once (even if the socket is in two or more rooms).

You can also broadcast to a room from a given socket.

io.on("connection", (socket) => {
  socket.to("some room").emit("some event");

In that case, every socket in the room excluding the sender will get the event.
IntroductionAboutSocketIO4.png To leave a channel you call leave in the same fashion as join.


Related Showcases



Some concepts in ES6

Contact Us