DEV Community

Cover image for Create a chat app with socket.io and node.js
EneasLari
EneasLari

Posted on

Create a chat app with socket.io and node.js

Hello guys,
In this article we are going to create a group chat app that can also be private.

Socket.io

Socket.io is the main package that we are going to use for our web app.
Socket.IO is a library that enables real-time, bidirectional and event-based communication between the browser and the server.

It consists of:

  • a Node.js server
  • a Javascript client library for the browser (which can be also run from Node.js)

Image description

So lets create a server for our web app:

Initialize a new node.js project:
npm init

Install express:
npm install --save express

Install socket.io:
npm install --save socket.io

Install ejs for server side rendering:
npm install --save ejs

The server code:

We use express framework for server, also in order to render a html page we use ejs.

The server handles the messaging between clients. It is the middleware for the message delivering.

The client code:

Lets explain the client code

First we define the room name. Here the room name is set to test for simplicity reasons but it can be dynamic. The room name is the name that will need every client in order to join the chat.

  • "created" event, will be received from the first user that will join the room and this client will flagged as the initiator of the room.

  • "create or join" is the event that every user that joins the room will call.

  • "join" event will received from all clients when a new one enters the room and will inform them about his information (in our situation only his name)
    Also in this event the initator will send an event only for he new user that joined the room to update his list of other clients in the room.

  • "beforeyou" event will received only by the last user that will join the room to update his list of the users already existing in the room.

  • "message" event is the main event that every user will receive after the connection in the room is established

The view:

The full code on github with more detailed comments:
github

Top comments (0)