Connecting with websocket using SpringBoot and Angular4

Posted By : Abhishek Saini | 28-Oct-2017

WebSocket is a very thin, lightweight layer above TCP. It makes it very suitable to use "subprotocols" to embed messages. Here we use use STOMP messaging with Springboot.And on frontend side an angular4 application to send and receive mesaages.

From server side simply add this maven dependency to your pom.xml.

 

	org.springframework.boot
	spring-boot-starter-websocket


After adding dependency,make a class say WebSocketConfig something like:

 

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

	@Override
	public void configureMessageBroker(MessageBrokerRegistry config) {
		config.enableSimpleBroker("/topic");
		config.setApplicationDestinationPrefixes("/app");
	}

	@Override
	public void registerStompEndpoints(StompEndpointRegistry registry) {
		registry.addEndpoint("/connectTowebsocket").setAllowedOrigins("*").withSockJS();
	}

 

Your server side configuration is done.From the frontend we simply use ng2-stomp-service to send and receive message.

Install these npm module to use:

 
npm i --save stompjs
npm i --save sockjs-client
npm i --save ng2-stomp-service
 

In -> typings.d.ts

Add stompjs and sockjs-client module declaration

 declare module 'stompjs';
declare module 'sockjs-client';
 

In app.module.ts

 
import { StompService } from 'ng2-stomp-service';
 @NgModule({
  providers: [StompService]
})
 

Then create a service simply :

 
import { StompService } from 'ng2-stomp-service';
 
private subscription : any;
 
constructor(stomp: StompService) {
 
  //configuration 
  stomp.configure({
    host:"/connectTowebsocket",     //this is your endpoint url declared on server side to connect
    debug:true,
    queue:{'init':false}
  });
  
  //start connection 
  stomp.startConnect().then(() => {
    stomp.done('init');
    console.log('connected');
    
    //subscribe 
    this.subscription = stomp.subscribe('/topic', this.response});
    
    //send data 
    stomp.send('destination',{"data":"data"});
    
    //unsubscribe 
    this.subscription.unsubscribe();
    
    //disconnect 
    stomp.disconnect().then(() => {
      console.log( 'Connection closed' )
    })
    
  });
}

 

Hope this will help.

Thank you.

About Author

Author Image
Abhishek Saini

Abhishek is bright Lead developer with skills in AngularJS and Java. He loves to learn new technologies.

Request for Proposal

Name is required

Comment is required

Sending message..