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

Building a chat application step by step

Building a real time chat application will be the starting point for developing many applications with socket connections which will involve two way communication among server and client. So this chat application can be converted in to many other forms like multiplayer quiz games, state changing applications any many more. Here we will be developing the chat application using NodeJS back-end and Angular front-end. Further we will be using socket.io for socket communication. So to continue you need to have Angular and NodeJS pre-installed.

Creating the Node application

Our first task is to create the node project. To this I will create a empty directory called socket-backend and start teminal/command prompt from there. Then type “npm init” and press enter and keep default setting by pressing enter to make it simple.

Now you will be able to see package.json file has been created inside the folder. Then we will install express framework by typing

npm install express@4.15.2

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

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 node application. Next step is to setup server.js file to serve our application. So I will type following code inside it.

Now we can run the application by tying 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 “hello” text. If it is working, now you have a working node express application.

Now I will do few things to run our application more easily. First I will install nodemon by following command.

npm install nodemon

This package will monitor the application and run it again automatically when we make changes and save. So I do not need to run the application manually after each change. Then in I will go to package.json and add following command under “scripts”.

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

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

Integrating with socket.io

We can install socket.io to our application by simply running

npm install socket.io

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

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

and then I’ll add following lines to listen to the connection event for new incoming socket connections and log to console.

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

Now the complete server.js file look like this.

server.js / Server application

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

Creating Angular application

Lets 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 new project lets open it from our code editor. We can run our angular application by typing

ng serve

in the terminal. (By the way if you found an error while running the above command about rxjs 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 browser you will see the running angular application.

Now lets 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 see only “chat-inbox works!” in the browser. Next step is to install socket-client package in angular application. So let’s install that by

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 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 create a variable called “socket” to hold the socket created, function called “setupSocketConnection” to initiate the socket connection and include it inside ngOnInit as bellow.

So the complete chat-inbox.component.ts file look like this.

chat-inbox.component.ts / Client Application

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

Terminal / Server application

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

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

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

server.js

Now lets go to Angular application and make some changes to send and receive messages.

So I will go to 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 demonstrating purpose.)

chat-inbox.component.html
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.

app.module.ts

Now we can use ngModel to bind the input to a variable in chat-inbox. So I will go to chat-inbox.components.ts and create a variable called ‘message’ and bind that to input-box in chat-inbox.components.html.

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

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

chat-inbox.component.ts

Now if you type something in the input box and press send button you should see the message from node application console. The remaining part is to get that message by other users.

For that I will make some modification in setupSocketConnection function.

chat-inbox.component.ts

This will get the messages from socket and append that 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-inbox.component.ts

Now you can open our chat application from two browser tabs and test it by sending messages.

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

Next Steps

After building this you may find some limitations here. For example messages will get disappeared when user refresh the page. Further this will only support one chat room. We cannot create separate chat rooms or send individual messages to few people.

As next steps we can use a database to store the messages and then get the previous messages from the database if user refresh the page. Further more 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.)

Thanks for reading. 😊

Senior Software Engineer | Front-end Developer | Angular | Vue | Node | Flutter

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store