Socket.IO with Node.Js + Express

Sude Kılıç
Koçfinans Tech
Published in
5 min readDec 16, 2021

Nowadays, most web developers want to develop real-time web applications or customize their existing applications to become real-time in order to increase user satisfaction. Therefore, Websockets are becoming very common in the modern web development environment. Especially in areas like Chat Applications and Push Notifications, this need has become even more prominent.

What is WebSocket?

WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection.

WebSocket promotes real-time communication between the Client and the Web Server. It has the significant advantage of providing full-duplex communication over an HTTP connection. WebSocket also increases the accuracy and efficiency of stream events.

What is Socket.io?

Socket.IO enables real-time, bidirectional and event-based communication. It works on every platform, browser or device, focusing equally on reliability and speed.

Socket.IO is a JavaScript library for real-time web applications. It has two parts: a client-side library that runs in the browser, and a server-side library for Node.js. Socket.IO automatically upgrades the requirement to WebSocket if needed.

Difference Between WebSocket and Socket.io

It’s important to note that Socket.IO is not a WebSocket implementation. The authors state that:

“Socket.IO indeed uses WebSocket as a transport when possible, but a WebSocket client will not be able to connect to a Socket.IO server, and a Socket.IO client will not be able to connect to a WebSocket server”.

Here are some of the key differences between WebSocket and Socket.io

  1. WebSocket is the protocol that is established over the TCP connection, Socket.io is the library to work with WebSocket.
  2. WebSocket provides full-duplex communication on TCP connections, Socket.io provides the event-based communication between browser and server.
  3. WebSocket does not support Proxy and load balancer, with Socket.io a connection can be established in the presence of proxies and load balancers.
  4. WebSocket doesn’t support broadcasting, Socket.io supports broadcasting.
  5. WebSocket doesn’t have a fallback option, Socket.io supports fallback options.

Integrating Socket.io

You will need Node and npm installed before you can start creating apps with Socket.IO. You can run the following lines in your terminal to confirm that node and npm are installed.

node --version
npm --version

After making sure that Node and npm are downloaded, create a new file and set up the npm package to create a package.json configuration file.

Now we are ready to install Express and Socket.io

npm i --save express socket.io

Instead of using the node command, you can use nodemon to avoid restarting the server whenever a file changes.

npm i -g nodemon

If all these steps are done, let’s create a simple file called server.js.

const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const port = process.env.PORT || 8080;app.get('/', function(req, res) {
res.sendfile('index.html');
});
server.listen(port, function() {
console.log(`Listening on port ${port}`);
});

And, we need an index.html file.

<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
</head>
<body>Integrating Socket.io with Node.js and Express</body>
</html>

You can test it by running the nodemon command, this command will run the server on localhost:8080. If you go to your browser and enter localhost:8080, you can see that the application is running. Now, let’s continue with socket.io.

io.on('connection', (socket) => {
socket.emit('connect', {message: 'a new client connected'})
})

The critical parts of this code block are the io.on and socket.emit functions.

The io.on function triggers a sequence of actions when a connection arrives. The codes in this function will only work if the connection is received. This event handler uses the socket object to handle connection, disconnection, events, and more.

The Socket.IO API is inspired by the Node.js EventEmitter, which means you can emit events on one side and register listeners on the other. The socket.emit function takes an emit name as its first argument. You can specify this name and listen to it on the client-side according to this name. The second argument should be the data you want to send.

For example, you may add features like broadcasting a message to the entire chat group. In other words, a message can be sent to all users who are currently connected to the socket port.

socket.on('chat', message => {
// console.log('From client: ', message)
io.emit('chat', message)
})

Of course, the client has to listen to the event emitted by the server.

socket.on('chat', message => {
console.log('From server: ', message)})

For now, let’s move on with logging to see if it works properly. The final version of server.js is as follows.

const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
const port = process.env.PORT || 8080;
app.get('/', function(req, res) {
res.sendfile('index.html');
});
io.on('connection', (socket) => {
console.log('user connected');
socket.on('disconnect', function () {
console.log('user disconnected');
});
})
server.listen(port, function() {
console.log(`Listening on port ${port}`);
});

After logging messages on connections and disconnections, the client script must be included to initialize the socket object so that clients can create connections as needed. io server serves the script at ‘/socket.io/socket.io.js’.

<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
const socket = io();
</script>
<body>Integrating Socket.io with Node.js and Express</body>
</html>

All set! If you go to your browser and enter localhost:8080, you can see that the server logs the message ‘user connected’. Each time you refresh your browser, it will first disconnect the socket connection(‘user disconnected’) and then recreate a new one (‘user connected’).

It’s that easy to connect to Socket.io with Node.js and Express. The Socket.io also offers different features that you can use according to your own needs such as a few examples below.

socket.to($client-id): sending a message from a client to just one client
io.sockets: sending messages to all clients connected to the server with Socket.io
socket.brodcast: communicating with other clients from a client with Socket.io.

You can find more detailed information in the documentation.

Thanks to the features and methods in Socket.IO, real-time applications can be developed easily. However, when there is a problem on the server and client-side, it will be beneficial to take good action without reflecting this problem on the user.

Take care!

--

--