Skip to main content

Real time chat application using Angular, NodeJS and socket.io

Building a chat application step by step

Building a real time chat application is the starting point for developing many applications with socket connections, which involve two way communication between server and client. This chat application can be converted to other apps such as multiplayer quiz games, state changing applications and more. In this post, it will be explained how to develop a chat application using NodeJS back-end and Angular front-end. Furthermore, we will be using socket.io for socket communication. Therefore, to continue, you need to have Angular and NodeJS pre-installed.

 

Creating the Node application

Our first task is to create the Node project. For that, an empty directory called socket-backend will be created and terminal/ command prompt will be started from it. Then type “npm init” and press enter and keep default settings by pressing enter to keep it simple.

 

Chat App 1

 

Now you will see package.json file created inside the folder. Then we will install express framework by typing

npm install [email protected]

in terminal. After that let’s create the following folder structure for our application.

 

Chat App 2

 

This contains a folder ‘routes’ with ‘index.js’ file inside it and a file called server.js in the main directory which will be the starting point for the Node application. Next step is to setup server.js file to serve our application. For that, the following code is typed inside it.

 

 

Now we can run the application by typing the following command in terminal.

node server.js

 

This will listen to port 3000. If you go to localhost:3000 on your browser you should able to see the text “hello”. If so, you now have a working node express application.

Now, a few more things for the application to run even more easily. First, I will install nodemon using the following command.

npm install nodemon

This package will monitor the application and run it again automatically when we make changes and save. There is no need to run the application manually after each change. Then the following command will be added in package.json under “scripts”.

"scripts": {  
    "serve" : "nodemon server.js" 
},

 

Chat App 3

 

Now we can run the application by “npm run serve”.

 

Integrating with socket.io

We can install socket.io by simply running,

npm install socket.io

 

Then we must import socket.io to server.js file by adding

var io = require('socket.io')(http);

and then the following lines will be added to listen to the connection event for new incoming socket connections and log into the console.

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

 

The completed server.js file looks like this.

 

Chat App 4
                                        server.js / Server application

 

Let’s keep this aside for a moment and create the angular client to start the connection.

 

Creating Angular application

Let’s create a new angular project called socket-frontend. For that, I will go back to the main directory in terminal and type,

ng new socket-frontend

 

After creating the new project, let’s open it from the code editor. We can run the angular application by typing,

ng serve

in the terminal. (Note: if you encounter an error about rxjs while running the above command, update the package.json file “rxjs”: “.0.0 with rxjs”: “6.0.0” and run npm install).

ng serve will run the angular application in default port 4200. If you go to localhost:4200 from the browser you will see the angular application running.

 

Now let’s create a new component by

ng g c chat-inbox

and use that component by updating app.component.html file to

<div>  
   <app-chat-inbox></app-chat-inbox> 
</div>

 

Now you will only see “chat-inbox works!” in the browser. Next step is to install the socket-client package in angular application. So let’s install that with,

npm install socket.io-client

 

Now we can start using socket.io-client package. Although it is better to use a separate service file to handle socket connections, I will handle the socket connection in the chat-inbox.component.ts file to make it more simple.

 

First I will create a constant for socket endpoint in chat-inbox.component.ts

const SOCKET_ENDPOINT = ‘localhost:3000’;

 

Then I will create a variable called “socket” to hold the socket created. Use the function called “setupSocketConnection” to initiate the socket connection and include it inside ngOnInit as below.

 

 

The completed chat-inbox.component.ts file looks like this.

 

Chat App 5
                                   chat-inbox.component.ts / Client Application

 

Now you can go to the (running) angular application using any browser while the node application is running. Then you will see the text, “user connected” in the node application terminal.

 

Chat App 6
                                                                      Terminal / Server application

 

If you got this, cheers! You have successfully connected the angular socket client to node socket server.

Our next task is to create a methods to receive messages from a client and send them to other clients in real-time. For that I will go to node application server.js file and update following code as shown below. 

 

 

This will watch the “message” event to get a message from the client side and then emit that message to “message-broadcast” event from sever-side.

 

Chat App 7
                                                       server.js

 

Now let’s go to the Angular application and make some changes to send and receive messages.

I will go to the chat-inbox.component.html file and add some containers to show the messages and message submission area to type and send a message. Further I will go to chat-inbox.component.css file and add some styles to make it nice. (I have added some styles, only for demonstration purposes).

 

 

chat-inbox.component.html
                                                           chat-inbox.component.html

 

 

Chat App 9
                         chat-inbox.component.css

 

To use Angular forms I will go to app.module.ts and import the FormsModule using

import { FormsModule } from ‘@angular/forms’; 

and use it inside the imports array.

 

Chat App 9
                                                           app.module.ts

 

Now we can use ngModel to bind the input to a variable in chat-inbox. Therefore, a variable called ‘message’ is created in chat-inbox.components.ts and it is bound to input-box in chat-inbox.components.html.

 

Chat App 10
                                      chat-inbox.component.ts

 

Chat App 11
                                                             chat-inbox.component.html

 

Now we can go to chat-inbox.components.ts and update the send message function.

 

 

Chat App 12
                               chat-inbox.component.ts

 

Now if you type something in the input box and press ‘send’ button you should be able to see the message from node application console. What is remaining is to make it so that the other users also will receive the message.  

For that I will make some modifications in setupSocketConnection function.

 

 

Chat App 13
                                                      chat-inbox.component.ts

 

This will fetch the messages from socket and append it to “message-list” element.

In the chat-inbox we should show sent messages as well. For that we will modify send message function as follows.

 

 

Chat App 14
                                                       chat-inbox.component.ts

 

Now you can open the chat application in two separate browser tabs and test it by sending a test message.

 

Chat App 15

 

Finally we have completed creating a chat application with socket.io. This can send messages in real-time to any number of users. You can customise this application with your own styles and concepts.

 

Next Steps

After building this you may come across some problems. For e.g. messages disappear when users refresh the page; this supports only one chat room; separate chat rooms cannot be created nor individual messages can be sent to a group of people.

As a solution we can use a database to store the messages and retrieve the previous messages from it when the user refreshes the page. Furthermore, socket.io supports chat room facility and you can improve this app to create chat rooms and send messages to specific chat room.

(Hope to bring them in a future article.)


LEAVE A COMMENT







POST COMMENTS


© 2020 Creative Software. All Rights Reserved | Privacy | Terms of Use