Real-time chat application using Ionic 2 and sockets.io
Hi friends,
Hope you are all doing good. In this post I will show you how to use sockets to build a real-time chat application using Ionic 2. We will be using a nodejs app for backend(along with sockets) and Ionic 2 (along with sockets-client) in the front-end.
The complete code of this tutorial can be found here:
Backend – Click here.
Front-end – Click here.
A screencast of this tutorial:
Let’s get started.
First create a nodejs app and install sockets.io using the following commands one by one. (Better do this inside a new directory).
Now create a new file index.js in the project directory and enter the below code.
Let’s break this down.
- We have created a simple http server that runs on port 3000.
- We have made the variable io listen to this server. This is actually the socket.io object.
- Upon receiving an incoming connection it will generate a socket which can then be used to listen for messages from that connection.
- We emit the message to other connected clients listening on that flag (Here it is message).
Now save this code and start the app using the command
1
|
node index.js
|
Our back-end is ready.
Create a front-end app using blank template of Ionic 2.
Navigate to www/index.html and add the below line of code in
(Add this line just above the <script src=”cordova.js”></script> line).
Now open up home.html file and add the below code.
Now we have a list for displaying the messages and an input field and a button for sending out our chats.
Now open up home.js file and add the below code.
Let’s break this down.
- We have a send method which will send our message to the server.
- We have a socket.on listener which listens for incoming messages and adds them to the array chats. (Note the use of zone to update the DOM in realtime).
That’s it guys. Now if you run the app(Backend should be running as well) you should see an awesome app through which you could chat or send messages in real time.
Thanks for reading guys. Peace.
No comments: