Learn Exactly How To Integrate Socket.io In Ionic 3

Integrate Socket.io In Ionic 3

Socket.IO:-
 

Socket.io gives real-time two directional event-based communication. It plays its role on every platforms, browsers and device, providing the actual reliability and speed while communicating. socket.io is one of the most used libraries of npm.

 

Socket.io is a library built on javascript for real-time applications. It provides the feature of real-time, communication between clients and servers. So it has two sides one client-side library which runs on the browser and server-side script which runs on the node. Both ends having connected APIs.

 

Now let’s check how we can integrate socket.io with ionic 3 so that ionic3 will be used as client and node js will be used as a server and both of side integrate socket.io

 

Steps:- 
 

   Client-side code:- 

 

  • Let’s create a blank Ionic app and then install the ng-socket-io package for connection between socket backend and ionic as front end and add the new page. so run these commands
ionic start chatApp blank
cd chatApp
npm install ng-socket-io --save
ionic g page chatting

 

  • Now we need to add a socket.io package in our app.module.ts file so that it will be available to us in whole application and add backend URL as a parameter
import { SocketIoModule, SocketIoConfig } from 'ng-socket-io';

	const config: SocketIoConfig = { url: 'http://localhost:3001', options: {} };
	@NgModule({
		imports: [
			….
SocketIoModule.forRoot(config)
….
]
})

 

  • Here user needs to enter the name to join a room. So for that add this code in home.ts file
<ion-header>
  <ion-navbar>
<ion-title>
     		 Join chatroom
    	</ion-title>
  </ion-navbar>
</ion-header>
 
<ion-content padding>
  <ion-item>
<ion-label stacked>Set Nickname</ion-label>
<ion-input type="text" [(ngModel)]="nickname" placeholder="Nickname"></ion-input>
  </ion-item>
<button ion-button full (click)="joinChatRoom()" [disabled]="nickname === ''">Join Chat Room {{ nickname }}</button>
</ion-content>

 

  • Then add this piece of code at home.ts file for setting nickname for socket.io
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Socket } from 'ng-socket-io';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})


export class HomePage {
  nickname = '';
  constructor(public navCtrl: NavController, public socket: Socket) { }
 
  joinChatRoom() {
    this.socket.connect();
    this.socket.emit('set-nickname', this.nickname);
    this.navCtrl.push('ChattingPage', { nickname: this.nickname });
  }
}

 

  • Now add this code to our chatting.ts file for send and get all the chats

import { Component } from '@angular/core';
import { NavController, IonicPage, NavParams, ToastController } from 'ionic-angular';
import { Socket } from 'ng-socket-io';
import { Observable } from 'rxjs/Observable';
 
@IonicPage()
@Component({
  selector: 'page-chat-room',
  templateUrl: 'chat-room.html',
})

export class ChattingPage {
  messages = [];
  nickname = '';
  message = '';

constructor(private navCtrl: NavController, private navParams: NavParams, private socket: Socket, private toastCtrl: ToastController) {

    this.nickname = this.navParams.get('nickname');

    this.getMessages().subscribe(message => {
      this.messages.push(message);
    });
 
    this.getUsers().subscribe(data => {
      let user = data['user'];
      if (data['event'] === 'left') {
        this.showToast('User left: ' + user);
      } else {
        this.showToast('User joined: ' + user);
      }
    });
  }
 
  sendMessage() {
    this.socket.emit('add-message', { text: this.message });
    this.message = '';
  }
 
  getMessages() {
    let observable = new Observable(observer => {
      this.socket.on('message', (data) => {
        observer.next(data);
      });
    })
    return observable;
  }
 
  getUsers() {
    let observable = new Observable(observer => {
      this.socket.on('users-changed', (data) => {
        observer.next(data);
      });
    });
    return observable;
  }
 
  ionViewWillLeave() {
    this.socket.disconnect();
  }
 
  showToast(msg) {
    let toast = this.toastCtrl.create({
      message: msg,
      duration: 2000
    });
    toast.present();
  }
}

 

  • Then add this code in chatting.html file

<ion-header>
  	<ion-navbar>
    	  <ion-title>
      		Chat
   	 </ion-title>
  	</ion-navbar>
</ion-header>
 
<ion-content>
  <ion-grid>
    <ion-row *ngFor="let message of messages">      
      <ion-col col-9 *ngIf="message.from !== nickname" class="message" [ngClass]="{'my_message': message.from === nickname, 'other_message': message.from !== nickname}">
        <span class="user_name">{{ message.from }}:</span><br>
        <span>{{ message.text }}</span>
        <div class="time">{{message.created | date:'dd.MM hh:MM'}}</div>
      </ion-col>
 
      <ion-col offset-3 col-9 *ngIf="message.from === nickname" class="message" [ngClass]="{'my_message': message.from === nickname, 'other_message': message.from !== nickname}">
        <span class="user_name">{{ message.from }}:</span><br>
        <span>{{ message.text }}</span>
        <div class="time">{{message.created | date:'dd.MM hh:MM'}}</div>
      </ion-col>
 
    </ion-row>
  </ion-grid>
 
</ion-content>
 
<ion-footer>
  <ion-toolbar>
    <ion-row class="message_row">
      <ion-col col-9>
        <ion-item no-lines>
          <ion-input type="text" placeholder="Message" [(ngModel)]="message"></ion-input>
        </ion-item>
      </ion-col>
      <ion-col col-3>
        <button ion-button clear color="primary" (click)="sendMessage()" [disabled]="message === ''">
        Send
      </button>
      </ion-col>
    </ion-row>
  </ion-toolbar>
</ion-footer>

 

Server code:-

  • Now as we are almost done with the client side code, let’s start with the backend for our app. It would be essential to have a bit of knowledge about Node js so you could potentially build your own little backend at any time. First of all, let’s create a new folder and install Express as a minimal require a framework for our backend.

mkdir SocketServer
cd SocketServer
npm install express --save
npm install --save socket.io

  • Now create a new package.json file in the SocketServer folder.

{
  "name": "socket-server",
  "version": "1.0.0",
  "main": "index.js",
  "dependencies": {
    "express": "^4.15.3",
    "socket.io": "^2.0.3"
  }
}

 

  • Then create an index.js file and add this code

let express  = require('express');
let app      = express();
let http = require('http').Server(app);
let io = require('socket.io')(http);
 
io.on('connection', (socket) => {
  
  socket.on('disconnect', function(){
    io.emit('users-changed', {user: socket.nickname, event: 'left'});   
  });
 
  socket.on('set-nickname', (nickname) => {
    socket.nickname = nickname;
    io.emit('users-changed', {user: nickname, event: 'joined'});    
  });
  
  socket.on('add-message', (message) => {
io.emit('message', {text: message.text, from: socket.nickname, created: new Date()});    
   });
});
 
var port = process.env.PORT || 3001;
 
http.listen(port, function(){
   console.log('listening in http://localhost:' + port);
});

 

Hope this helps you well, feel free to add your comments/feedbacks. Need more assistance regarding Ionic App Development Get in touch today!