Learn Socket.io in 2 Hours

Learn Socket.io for both the server and client-side

Software Notebook
4 min readAug 20, 2021

The Purpose of WebSockets

WebSocket is a communication protocol that provides a bidirectional communication channel between a server and client over HTTP through a TCP connection.

This may be confusing, but all you need to understand is that WebSockets allow the connection between client and server to persist.

In a regular client-server transaction, the client would get the data they need from the server then close the connection. If the client needs 10 pieces of information they have to make 10 requests.

With WebSockets, on the other hand, the client can connect to the server and have that connection stay open. So the client can make 10 requests with just 1 connection.

WebSockets are perfect for applications that require real-time data transfer.

What is Socket.io?

Socket.io is a simple-to-use library that uses WebSockets to enable real-time bidirectional communication between client and server.

Socket.IO is composed of two parts:

  • A server that integrates with (or mounts on) the Node.JS HTTP Server
  • A client library that loads on the browser side

First, we’ll set up Socket.io on an Express server

Socket.io on the Server

First, install the package to use Socket.io (npm install socket.io). In your server file, import Socket.io.

const socketio = require('socket.io');

You’ll also need to import the HTTP module and create an HTTP server:

const http = require('http');
const server = http.createServer(app);

http.createServer is used by Express under the hood, but we will need to access it directly to use Socket.io.

Using the HTTP server, we create an io object:

const io = socketio(server);

Socket.io Methods on the Server

The io.on(‘connection’, …) method runs every time a client connects to our server. All of the other Socket.io logic goes inside the callback function of this method.

io.on(‘connection’, socket => {
// all socket logic
});

The first argument socket is the user’s Socket instance.

socket.on() listens for events from the client. In the parentheses put the specific String name of the event to listen for. The client can optionally pass data which can be accessed the function’s callback. Here’s an example:

socket.on("message", text => {
console.log("New message: {text}")
})

In the above example, the string "message" is a custom event emitted from the client whenever a new message is sent. The client sends text data along with the event which can be accessed in the callback function.

io.emit() sends, or emits, an event to all connected clients, including the sender. The syntax is similar to the previous method we discussed. The server can pass data as an optional parameter in this method.

io.emit("alert", 'some alert data')

socket.broadcast.emit(“message”)sends an event to all connected clients, except the one that sent the message.

socket.join(room) adds the user’s socket to a room. A room is an arbitrary channel that sockets can join and leave. It can be used to broadcast events to a subset of clients.

io.in('game').emit('message', data) sends an event to all clients in game room (channel), including the sender.

socket.to(id).emit(“message”, data)sends an event to an individual socket by putting their id in the to() method.

You can also use this method to send an event to a room with multiple sockets (similar toio.in()) by passing the room name/id in the to() method.

socket.on(‘disconnect’, () => {}) is fired by the Socket instance upon disconnection.

Socket.io on the Client

If you are using a frontend framework such as React or Vue, you need to install the Socket.io client library in your project folder (npm install socket.io-client).

In your working file, import io from the client library:

import { io } from 'socket.io-client'

Then, create a socket on the frontend by calling the io function and passing in the address of your server.

const socket = io('http://localhost:3000')

Use socket.on('event', data => {}) to listen for and handle events from the server:

// Receive message from server and output it to screen
socket.on('message', (message) => {
outputMessage(message);
});

Use socket.emit('event', data) to send events to the server:

socket.emit('joinRoom', { username, room });

Example Socket.io Implementation

I’m going to give a simple example of a situation where a user can send a message to the server and the server will broadcast the message to all of the users. This is similar to what you would need to do in a chat application.

On the client, this function sendMessage emits an event called‘sendMessage’ to the server and includes an object with a username and message.

const sendMessage = (message) => {
socket.emit('sendMessage', { username, message });
}

On the server, we are listening for the ‘sendMessage’ event from the client. If the event occurs, we broadcast an event containing the username and message to all connected clients using io.emit().

io.on('connection', socket => {   socket.on('sendMessage', ({ username, message }) => {
io.emit('newMessage', { username, message })
});
}

On the client, this method is listening for the ‘newMessage’ event from the server. If a message is recieved, it shows the the message on the screen.

socket.on('newMessage', ({ username, message }) => {
showMessage('Message from {username}: {message}');
}

--

--

Software Notebook

I’m Josh and I write articles to help you with software development, data science, and more.