Codementor Events

Build a chat web-app with node.js and socket.io (including private messaging).

Published Dec 24, 2018

Go to the profile of ashay mandwarya

ashay mandwaryaBlockedUnblockFollowFollowing

Nov 4

Messaging apps are surging in popularity nowadays, there are literally thousands of chat based apps and they are also very popular among the users as they provide a personal touch while connecting the world together.


Socket.io logo (Socket.io website)

To build a real time chat application, there should be a real-time system for sending-receiving data. This can be attained using web-sockets. Instead of using the web-sockets API directly we will be using socket.io. We will also be using Express.io with node.js so as to simplify building the web-app more simple.

The tutorial will mostly include the back-end part and readers can use any of the available css libraries for UI part.

We will be using Visual Studio Code for the project.

— Build the server

npm init

This will start a new project, provide all the information required. It will look like this.

{
  "name": "app",
  "version": "1.0.0",
  "description": "Chat app",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "Ashay Mandwarya",
  "license": "ISC"
}

Install the dependencies.

npm install --save socket.io express

This will install all the dependencies and now we can start coding for the server.

Create two files in the project folder as server.js and index.html. Open server.js.

In server.js start with the following code-

var express=require('express');

var app=express();

app.get('/',function(req,res){

res.sendFile(__dirname+'/index.html');

});

var server=require('http').Server(app);

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

server.listen(3000);

The above code sets up the basics for setting up the server. It uses both socket.io and express dependencies to create the server. The last line starts the server at port 3000.

Setting up the client

It’s pretty simple. Open index.html and get started with the below code.

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<script src="/socket.io/socket.io.js"></script>

</head>

<body>

<div id="box">

</div>

<form id="register">

<input type="text" id="name">

<input type="submit" value="Submit">

</form>

<form id="chat">

<input type="text" id="to">

<input type="text" id="message">

<input type="submit">

</form>

<script>

var socket=io.connect();

</script>

</body>

</html>

Line number 9 and the content in the last script tag are the only requirement to make your client chat ready.

Let’s start writing the code for real time messaging.


Code for the app

index.html

  • Line 25 => Line 25 is just a shorthand for document.ready(function(){}). Below that all the elements the buttons the text-box are associated with a variable, and if you have used events in javascript before, you know how simple this makes things.
  • Line 30 => Line 30 acts when you enter your name and press submit. This registers a user with the server and emits an event. These events arise from socket.io. You just have to name the event and write a function, based on what you want to do with the event with the data you want to send to others.
  • Line 46 => Line 46 acts up when we enter the name of the receiver with the message. The event is named as msg. It send the details of the receiver with the message to the server.
  • Line 53 => Line 53 responds to an event raised by the server and is used to receive message from other clients.

server.js

When a new client connects to the server socket.io raises an event called connection. The connection event states that a new client has been connected to the server. This helps keep track of how many and what with the clients.

  • Line 12 => This line reacts to the connection event and you can do like a welcome message or a successful connection message.
  • Line 14 => Line 14 responds to the new event emitted by the client in line 30. After receiving the event it responds with a function which takes in the data and a callback function. The data in the name of the client. It checks if the name is an unique entry in the users objects to keep track and users unique. The callback function responds back with the true or false based on the validation of unique user. After the callback the client receives the value as true or false and responds accordingly.
  • Line 26 => Line 26 responds to the msg event of the client. It also has a function which takes the parameters data and an callback function. Here the callbacks function is only to send the data back yo the user so that it can append the message in the chat box which can easily be done on the client side too. This is just to demonstrate the use of callbacks. Line 29 is the most important line which helps in creating private chat rooms which are most important to achieve private chats. It takes in the receivers name and creates a room with the client and receiver and send the message to the room.

This is the most basic chat app we can create. It is small and light weight but effective. You can add your functionalities in the app with a better UI and you are good to go.

Discover and read more posts from Ashay Mandwarya
get started
post comments2Replies
Yuliia
6 years ago

At the moment, there are various frameworks and APIs which can help greatly with the process. There also ready solutions, providing easy chatbots for those who are limited in resources. Depending on the complexity and design of an application, a chatbot can contain various features. Those mainly depend on the purpose of the app but also on the field of usage, and the type of technology used. The cost to make a chatbot will also vary in accordance with the number of options and the software. If anyone is interested in looking at this more precisely, here it is https://jelvix.com/blog/the-cost-of-chatbot-development

Ashay Mandwarya
6 years ago

But the control we get doing it in vanilla is unparalleled. Frameworks and APIs help, but if we want to learn something first we have to get our hands dirty like this.