Web Socket implementation in angular 4
Posted By : Vishal Kumar | 25-Nov-2017
Websocket is mainly used for real time messaging. It is very simple in implementation with stomp and sockjs in angular 4. These are the libraries easily accessible using npm. So below are the steps for websocket implemetation.
Step 1: First of all install these three libraries using npm. With the help of these libraries we don't need any extra configurarion.
1. npm i --save stompjs
2. npm i --save sockjs-client
3. npm i --save ng2-stomp-service
Step 2: Now we have to just import the StompService in our main module that is our App.Module.ts file and also pass it in providers of NgModule.
import { StompService } from 'ng2-stomp-service';
@NgModule({
...
providers: [StompService]
})
Step 3: It is the all configuration of web socket. Now we have to just create a service(WebSocketService) for connecting, subscribing messages and sending messages and also for disconnecting if there is need.
import { Injectable } from '@angular/core';
import { StompService } from 'ng2-stomp-service';
@Injectable()
export class WebSocketService {
private subscription : any;
constructor(stomp: StompService) {
//configuration
stomp.configure({
host:'test.com',
debug:true,
queue:{'init':false}
});
//start connection
stomp.startConnect().then(() => {
stomp.done('init');
console.log('connected');
//subscribe
this.subscription = stomp.subscribe('/destination',
this.response);
//send data
stomp.send('destionation',{"data":"data"});
//unsubscribe
this.subscription.unsubscribe();
//disconnect
stomp.disconnect().then(() => {
console.log( 'Connection closed' )
})
});
}
//response
public response = (data) => {
console.log(data)
}
}
Here test.com is the address of host where we want to connect and want to send and receive messages.
Conclusion: So this the simple way of web socket implementation in angular 4 using npm libraries stomp and sockjs. Stopm also provide us extra features like if our socket connection is broken without any reason then it will try to connect again automatically in every second. Benifit of creating WebSocketService is that we can easily reuse this service if we want to use websocket more than one component in angular 4 then we can just import this service and use it.
Thanks,
I hope this will be helpful
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Vishal Kumar
Vishal Kumar is Master in Computers Application. He has good technical skills in Java and always motivated to learn new things.