Chat server in Nodejs and Angular2

Http request is stateless in nature. It means that once the request and response gets processed , the connection gets closed. Again , if they want to request some thing again the server needs to do 2-way hand shake. But if we need the live application , like chat , dynamic graphs. We have to constantly open the socket. We do not want to request server again and again. For this we will use socket programming. In this architecture if any request arises from the client end , it immediately hits the server.

On node js ,we have a fantastic module socket.io. Let us see the code :

var app = require('express')();

var app = require('express')();
var http = require('http');
var server = http.createServer(app);

var io = require('socket.io').listen(server);

io.on('connection',function(socket){ 
console.log('Socket connection established4..') 
socket.on('join',function(data){ 
console.log('New joinee ',data) 
socket.join(data.room) 
socket.broadcast.to(data.room).emit('new joinee',{user : data.user,message : ' has joined group '+data.room}); })

socket.on('send_message',function(data){ console.log('The new message is ',data) io.in(data.room).emit('new_message',{user : data.user,message : data.msg}) })})
server.listen(3001,function(){ console.log('server connected')})

Now lets, work on the angular2 side :

step 1 : Create a service class

import { Injectable } from '@angular/core';
import * as io from 'socket.io-client';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class MyChatService {
privatesocket=io('http://localhost:3001');

sendMessage(data) {
this.socket.emit('send_message', data)
}

joinRoom(data) {
console.log('Inside the join service')
this.socket.emit('join', data)
}

newJoinee() {

varobservable=newObservable(observer=> {
this.socket.on('new joinee', function (data) {
observer.next(data)
})
})

return observable;
}

newMessage() {
varobservable=newObservable(observer=> {
this.socket.on('new_message', function (data) {
observer.next(data)
})
})
returnobservable;
}
}

Step 2 : Create component

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { MyChatService } from '../services/mychat.service';
@Component({
selector:'app-chat2',
templateUrl:'./chat2.component.html',
styleUrls: ['./chat2.component.css'],
providers: [MyChatService]
})
export class Chat2Component implements OnInit {
privatemsg:string;
privateroom:string;
privateuser:string;
privatemessages:any[]=[];
constructor(privatex:MyChatService) {

this.x.newJoinee().subscribe(res=> {
console.log('the new response is ', res)
this.messages.push(res)
})

this.x.newMessage().subscribe(res=>{
this.messages.push(res)
})

}

ngOnInit() {
}

onChange(ev) {
this.room=ev;
console.log('New user joined room')
this.x.joinRoom({ room:this.room, user:this.user });
}

sendMessage() {
this.x.sendMessage({room :this.room,user :this.user,msg :this.msg});
this.msg='';
}

}

Step 3 : Create chat html file

<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<!------ Include the above in your HEAD tag ---------->

<div class="container">
<divclass="row">
<divclass="col-md-5">
<divclass="panel panel-primary">

<!-- head start -->
<divclass="panel-heading">
<spanclass="glyphicon glyphicon-comment"></span> Chat

<!-- <div class="btn-group pull-right"> -->
<divclass="col-lg-12">
<inputclass="form-control" [(ngModel)]="user"placeholder="Your name..">
</div>
<divclass="col-lg-12"style="margin-top:20px;">
Join Group : <br>
<inputtype="radio" [(ngModel)]="room"value="1" (change)="onChange(1)"> Javascript
<inputtype="radio" [(ngModel)]="room"value="2" (change)="onChange(2)"> Java
<inputtype="radio" [(ngModel)]="room"value="3" (change)="onChange(3)"> Python
</div>


<!-- <button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
<span class="glyphicon glyphicon-chevron-down"></span>
</button> -->
<!-- <ul class="">
<li>Javascript</li>
<li>Java</li>
<li>Python</li>
</ul> -->
<!-- </div> -->
</div>
<!-- head end -->

<!-- body start -->
<divclass="panel-body">
<ulclass="chat">
<liclass="left clearfix" *ngFor="let x of messages">
<spanclass="chat-img pull-left">
<imgsrc="http://placehold.it/50/55C1E7/fff&text=U"alt="User Avatar"class="img-circle" />
</span>
<divclass="chat-body clearfix">
<divclass="header">
<strongclass="primary-font">{{x.user}}</strong>
<smallclass="pull-right text-muted">
<spanclass="glyphicon glyphicon-time"></span>12 mins ago</small>
</div>
<p>
{{x.message}}
</p>
</div>
</li>
</ul>
</div>
<!-- body end -->

<!-- footer start -->
<divclass="panel-footer">
<divclass="input-group">
<inputid="btn-input" [(ngModel)]="msg"type="text"class="form-control input-sm"placeholder="Type your message here..."
/>
<spanclass="input-group-btn">
<buttonclass="btn btn-warning btn-sm"id="btn-chat" (click)="sendMessage()">
Send</button>
</span>
</div>
</div>
<!-- footer end -->
</div>
</div>
</div>
</div>

 

Output :

By Pankaj Kumar Agarwal

 

Leave a reply:

Site Footer