DEV Community

Bliss Abhademere
Bliss Abhademere

Posted on • Updated on

Integrate your Node.js and Express.js App with Socket.IO

Image description

Introduction

Integrating Node.js, Express.js, and Socket.IO is required when creating real-time online applications. These technologies provide server-side web development projects with quick, scalable, and user-friendly solutions.

You will discover how to combine these technologies in this tutorial to create a real-time chat application.

Prerequisites

  • Basic knowledge of Node.js, Express.js and JavaScript.

  • Node.js and npm installed on your machine.

Step 1: Install dependencies

Before starting, install the essential dependencies, including Node.js, Express.js, and Socket.IO. Use npm to accomplish this:

npm install express socket.io
Enter fullscreen mode Exit fullscreen mode

Step 2: Set up a basic Express.js server

Your chat application will be built on a simple Express.js server that you create in this phase. The code below creates an HTTP server by calling require("http") on an Express.js server. Server (app), which listens on a certain port:

const express = require('express');
const app = express();
const server = require('http').Server(app);
const port = process.env.PORT || 3000;

server.listen(port, () => {
  console.log(`Server started on port ${port}`);
});
Enter fullscreen mode Exit fullscreen mode

Step 3: Integrate Socket.IO

You must incorporate Socket.IO if you want to provide your chat application real-time capabilities. Add the following code to your Express.js server to accomplish this:

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

io.on('connection', socket => {
  console.log('User connected');

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});
Enter fullscreen mode Exit fullscreen mode

By supplying the server to require("socket.io") in this case, io is constructed. When a client connects to the server, the code then waits for a "connection" event to be produced. The code logs a message to the console to show that a connection has been formed when one is made. A "disconnect" event is released when a user disconnects, and the code writes a message to the console to let the user know that they have disconnected.

Step 4: Add chat functionality

You can now give your chat application conversation features after integrating Socket.IO. You can achieve this by issuing a chat message event to all connected clients after listening for a chat message event from the client.

io.on('connection', socket => {
  console.log('User connected');

  socket.on('chat message', message => {
    io.emit('chat message', message);
  });

  socket.on('disconnect', () => {
    console.log('User disconnected');
  });
});
Enter fullscreen mode Exit fullscreen mode

Here, the code uses socket.on('chat message', message => ... ) to monitor the client for a "chat message" event. The code utilizes the io.emit() function to send out a "chat message" event to all connected clients whenever a "chat message" event is received. In this manner, the message will be delivered to all connected clients, who will then be able to see it in the conversation.

Conclusion

Now that Node.js, Express.js, and Socket.IO have been integrated, you have the ideal basis for a real-time online application. On top of this foundation, you can keep expanding and investigate the fascinating possibilities of real-time web development.

Buy Me A Coffee

I appreciate you taking the time to read this😁. Please think about giving it a ❤️ if you found it useful and instructive and bookmarking✅ for later use. Please post your queries and remarks in the comments box if you have any. I'm eager to hear your thoughts. Up until then!

Top comments (4)

Collapse
 
teejay128 profile image
Joseph Taiwo

Great article

I just love how brief and concise the article is, the only problem I find in it is that it is quite confusing for someone with no knowledge of socket.io, as you only posted the code and what it does, but you didn't explain how the code works 🤷

In the end the purpose was just to give an overview of socket.io, and it delivered that successfully

You could have also added the benefits of socket.io

Collapse
 
blissfelix3 profile image
Bliss Abhademere

I appreciate you reading the article and taking the time to comment. I value your openness and sensitivity over the level of info offered. I totally agree with you that the article's goal was to give a general overview of socket.io, and I'm sorry if the use of code-only formatting confused readers who aren't familiar with the subject.

I'm delighted the article was clear and to the point for you. I'll make sure to take into account your recommendations for future articles to highlight the advantages of using socket.io and to provide more context and explanation for the code.

Once more, I want to thank you for your comments and for helping me get better at writing.

Collapse
 
teejay128 profile image
Joseph Taiwo

Why does this your response sound like something from chatGPT 😂😂

The article was really good oh boss, I also try to make my articles as brief and concise as this, it's not like I am an expert writer, I am also learning technical writing 🤲

Thread Thread
 
blissfelix3 profile image
Bliss Abhademere • Edited

The response is certainly generic but i can't access chatGPT at the moment. I didn't even know you were a Altschooler like me lol.
I have also updated it. Turns out that i had that written already on my medium but didn't update it here.