YouTube Icon

Code Playground.

How to Develop Chat Integration with Socket.io in Angular

CFG

How to Develop Chat Integration with Socket.io in Angular

In this section, we will concentrate to produce a simple converse communication withsocket.io in Angular. Then we will be developing a converse operation using NodeJS as a server, Angular as a client, andsocket.io for socket communication. Before we bandy further aboutsocket.io we first should know about WebSocket to fluently understand about socket.io. 

What's WebSocket 

WebSocket is bidirectional, a full- duplex protocol that's used in the same script of client- server communication, HTTP starts from ws// or wss//. It's a stateful protocol, which means the connection between client and server will keep alive until it's terminated by either party( client or server). After closing the connection by either of the client and server, the connection is terminated from both ends. 

When can a WebSocket be used 

  • Real-time web application
  • Online multiplayer Game
  • Chat application
  • Realtime notification 

What's socket.io 

is a library that enables low- quiescence, bidirectional and event- grounded communication between a client and a server. It's erected on top of the WebSocket protocol and provides fresh guarantees like fallback to HTTP long- polling or automatic reconnection. 

Preparation 

Before we start, please check if you have NodeJS and Angular installed. We'll be using aNode.JS app( server) and a Angular app( client) to demonstrate the use of Web Sockets. 

node -v //check node version

ng --version //check Angular version

Create Node App

In our project folder, we've to produce separate to be two sub flyers 

  • - server
  • - client

Initialize npm in server directory 

In server folder, we need to init the npm, this can be done by using npm init 

npm init

This will be creating a package.json file in the server directory, and this will allow us to install npm packages in our design and produce an index.js file. 

Install express and socket.io 

In server folder install this package 

npm i express socket.io

Setting up socket server 

produce file name index.js inside server folder. 

const app = require('express')();
const httpServer = require('http').createServer(app);
const io = require('socket.io')(httpServer, {
  cors: {origin : '*'}
});

const port = 3000;

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

  socket.on('message', (message) => {
    console.log(message);
    io.emit('message', `${socket.id.substr(0, 2)}: ${message}`);
  });

  socket.on('disconnect', () => {
    console.log('a user disconnected!');
  });
});

httpServer.listen(port, () => console.log(`listening on port ${port}`));

Now we've a server that's harkening on harborage 3000. The socket server is harkening for a connection event. When the app is connected to this server, it'll emit the connection events, and when the stoner leaves the runner, the dissociate event will be called. After the communication event is entered by our server, it'll shoot the communication to all our druggies who connected with the connection event and will admit the same communication. 

Setting up socket server 

To start the server, we can fluently running this command. 

node .

Create Client with Angular 

Initialize Angular app 

Navigate to the client folder and run this command to produce a new Angular app.

ng new chat-application

You can replace the converse- operation with any name for the Angular App name. 

Install socket.io client 

After creating the angular app, we need to install thesocket.io package to help us to communicate between client and server.

npm i socket.io-client

Create a socket service

We can induce a new service end using this command. 

ng g s socket

and same as like above command, we can change the converse service name to any name. After generating the converse service it'll produce 2 new lines inside the app folder,socket.service.ts and socket.service.spec.ts. Change the socket.service.ts file to be this

import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { io } from "socket.io-client";


@Injectable({
  providedIn: 'root',
})
export class SocketService {

  public message$: BehaviorSubject<string> = new BehaviorSubject('');
  constructor() {}

  socket = io('http://localhost:3000');

  public sendMessage(message: any) {
    console.log('sendMessage: ', message)
    this.socket.emit('message', message);
  }

  public getNewMessage = () => {
    this.socket.on('message', (message) =>{
      this.message$.next(message);
    });

    return this.message$.asObservable();
  };
}

In this file, we have formerly set up for the client to connect to our socket server running on port 3000.

Update app component file

After we induce the service and it's connected to our server now we can produce a element that will be using the service that we have created over, and change the app.component.ts 

import { Component } from '@angular/core';
import { SocketService } from './socket.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  newMessage = '';
  messageList: string[] = [];

  constructor(private socketService: SocketService){

  }

  ngOnInit(){
    this.socketService.getNewMessage().subscribe((message: string) => {
      this.messageList.push(message);
    })
  }

  sendMessage() {
    this.socketService.sendMessage(this.newMessage);
    this.newMessage = '';
  }
}

Update the HTML file

<div *ngFor="let message of messageList">
  <li>
      {{message}}
  </li>
</div>

<input
  [(ngModel)]="newMessage"
  (keyup)="$event.keyCode == 13 && sendMessage()"
/>
<button (click)="sendMessage()">Send Message</button>

Start Angular app

It's the final step to developing this simple app, we just start the Angular app using this command.

ng serve

Conclusion 

We've formerly erected our converse app, but this app you may find some limitations then. It only supports one converse room or sends an individual communication to a many people. 

As coming way we can use database to store the dispatches and also get the former communication from database. Further moresocket.io supports converse room and you can ameliorate this app to produce apartments and shoot communication to specific room. 




CFG