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 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('').listen(server);

console.log('Socket connection established4..') 
console.log('New joinee ',data) 
socket.join('new joinee',{user : data.user,message : ' has joined group '}); })

socket.on('send_message',function(data){ console.log('The new message is ',data)'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 '';
import { Observable } from 'rxjs/Observable';
export class MyChatService {

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) {

return observable;

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

Step 2 : Create component

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { MyChatService } from '../services/mychat.service';
styleUrls: ['./chat2.component.css'],
providers: [MyChatService]
export class Chat2Component implements OnInit {
constructor(privatex:MyChatService) {

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



ngOnInit() {

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

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


Step 3 : Create chat html file

<link href="//" rel="stylesheet" id="bootstrap-css">
<script src="//"></script>
<script src="//"></script>
<!------ Include the above in your HEAD tag ---------->

<div class="container">
<divclass="panel panel-primary">

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

<!-- <div class="btn-group pull-right"> -->
<inputclass="form-control" [(ngModel)]="user"placeholder="Your name..">
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

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

<!-- body start -->
<liclass="left clearfix" *ngFor="let x of messages">
<spanclass="chat-img pull-left">
<imgsrc=""alt="User Avatar"class="img-circle" />
<divclass="chat-body clearfix">
<smallclass="pull-right text-muted">
<spanclass="glyphicon glyphicon-time"></span>12 mins ago</small>
<!-- body end -->

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


Output :

By Pankaj Kumar Agarwal


Leave a reply:

Site Footer