Create a Spring boot WebSocket application for a specific user using spring boot + angular

Today I am going to develop a WebSocket application using angular and spring boot. For this, I will describe what is WebSocket and sockjs . And most importantly how we will connect the spring boot application to angular using sockjs and send message to a specific user.

What is Websocket?

According to wikipedia, WebSocket is a computer communications protocol, providing full-duplex communication channels over a single TCP connection. The WebSocket protocol was standardized by the IETF as RFC 6455 in 2011, and the WebSocket API in Web IDL is being standardized by the W3C.For more click here

Why Websocket?

In many application the Websocket is used to push message to a client for real-time update.We generally recommends websocket for real-time update for free and also it is faster than a traditional HTTP connections.

Lets starts developing with spring boot

In spring boot we have required of the following dependancy.

spring-boot-starter-webSocket dependency is required for use of SockJS and Stomp in our project.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

Create a configuraton class for Webcoket configuration WebsocketConfig.java

First I configured that dependency with creating WebSocketConfig class in my config package as below.

@Configuration
@EnableWebSocketMessageBroker
public class WelsocketConfig implements WebSocketMessageBrokerConfigurer {
	@Override
	public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) {
		stompEndpointRegistry.addEndpoint("/ws")
				.setAllowedOrigins("*")
				.withSockJS();
	}

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

Create a Controller class for sending notification NotificationController.java

@RestController
public class NotificationController {

	
	@Autowired
        private SimpMessagingTemplate template;

    //Send a message to a particular user
    @GetMapping("/sendNotification")
    public String sendNotification() {
    	template.convertAndSendToUser(userId, "/reply", message);
    	return "Notification send succefully";
    }
  //send message to all user
   @MessageMapping("/send/message")
    public void sendMessage(){
        this.template.convertAndSend("/message",  message);
    }
	
}


From that Simple Messaging Templatewe can  convertAndSend() method to send message to all user and convertAndSendToUser() method to send message to a particular user. If there is any data comes to that message broker it will automatically send that data using above configured endpoint called /ws with SockJS and Stomp.

You can find the source code on git here

Lets Start for Angular Devlopement

ng new Websocket-frontend

Inside the project we have to install tree libraries with commands:

npm install stompjs;
npm install sockjs-client

Create a service websoket.service.ts

import {Injectable} from "@angular/core";

var SockJs = require("sockjs-client");
var Stomp = require("stompjs");


@Injectable()
export class WebSocketService {

    constructor() { }

    connect() {
        let socket = new SockJs('http://localhost:8080/ws');
        // let socket = new SockJs(`http://localhost:8081/ws`);

        let stompClient = Stomp.over(socket);

        return stompClient;
    }
}

Inside app.component.ts please update the following

import {Component} from '@angular/core';
import {WebSocketService} from "./services/websocket.service";


@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
})
export class AppComponent {

 

    constructor(private webSocketService: WebSocketService) {

        let stompClient = this.webSocketService.connect();
  // For All user
   stompClient.connect({}, frame => {

     stompClient.subscribe('/topic/notification', notifications => {

        console.log(notifications.body);

      })

  });
 // For specific user
stompClient.connect({}, frame => {
            
      stompClient.subscribe('/user/userId/reply', data => {
                
                 console.log(data)

            })

        });
    }
}

You can find the front-end applucation from git here

Leave a Reply

Your email address will not be published.

Back To Top