Spring Boot + WebSockets + Angular 5 | ORIL

Spring Boot + WebSockets + Angular 5

Spring Boot + WebSockets + Angular 5

Hello guys! Here we will speak about how to set up Spring Boot project with Websocket messaging and Angular 5.

As an output of this topic you will get small chat built with Spring Boot and Angular 5.

Lets’s start

First of all, we will set up Java project for this. The pom.xml file will contain just two dependencies we need at the moment:

We just included spring-boot-starter-web and spring-boot-starter-websocket into the project and that’s pretty enough to be able to receive messages from outside.

Next step is to configure WebSockets. Let’s create class WebSocketConfiguration where we will put all settings we need to start with sockets.

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfiguration extends AbstractWebSocketMessageBrokerConfigurer{    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/socket")
                .setAllowedOrigins("*")
                .withSockJS();
    }

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

The class should be annotated with @Configuration and @EnableWebSocketMessageBroker annotations, and our config class should be extended from an AbstractWebSocketMessageBrokerConfigurer class. After that just two methods should be overrided:

First method:

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

Here we define the endpoint, that our clients will use to connect to the server. So, in our case the URL for connection will be https://localhost:8080/socket/.

Also we allow server to receive requests from any origin. And we told the we will use not “clean” websockets, but with SockJS.

Second method:

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

What we say here — is an app prefix. So, when our client will send message through socket, the URL to send will look approximately like this: https://localhost:8080/app/…/…

And also we said that for now we will have just one subscription — /chat. So clients will subscribe to this subscription and will wait from messages from the server.

And that’s it for configuration!

The last thing we need to add before starting using websockets — is the controller.

The same as @RequestMapping for RestController we need to use @MessageMapping for websockets.

So, here we set up @MessageMapping(“/send/message”), and once this URL will be triggered — we will simply send message to all clients subscribed to /chat subscription.

And that’s it for Back-End! Now we need to create Front-End part of the application to start the socket communication.

For Front-End we will use just recently released Angular 5 framework.

Let’s use Angular CLI for application creation.

In command line run ng new your-app-name-here. Output of this command will be fully create Angular application that we can just run with command ng serve.

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

  1. npm install stompjs
  2. npm install sockjs-client
  3. npm install jquery (just to quickly access the DOM elements)

Here the code from app.component.ts

import { Component } from '@angular/core';
import * as Stomp from 'stompjs';
import * as SockJS from 'sockjs-client';
import $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private serverUrl = 'https://localhost:8080/socket'
  private title = 'WebSockets chat';
  private stompClient;

  constructor(){
    this.initializeWebSocketConnection();
  }

  initializeWebSocketConnection(){
    let ws = new SockJS(this.serverUrl);
    this.stompClient = Stomp.over(ws);
    let that = this;
    this.stompClient.connect({}, function(frame) {
      that.stompClient.subscribe("/chat", (message) => {
        if(message.body) {
          $(".chat").append("<div class='message'>"+message.body+"</div>")
          console.log(message.body);
        }
      });
    });
  }

  sendMessage(message){
    this.stompClient.send("/app/send/message" , {}, message);
    $('#input').val('');
  }

}
  • So, in the initializeWebSocketConnection() method we define let ws = new SockJS(this.serverUrl). And our serverUrl is https://localhost:8080/socket. So, this is the endpoint that we added in the registerStompEndpoints() method in the server code.
  • After that we told our stompClient to subscribe to the “/chat” channel, that is defined in the WebSocketConfiguration class in Java application.

So, what this subscription means — is that whenever some server send messages to the channel “/chat”, all clients that are currently subscribed to it — will receive those messages.

  • Next important element is sendMessage(message) method in app.component.ts. Here we simply take the message submitted from the input in html file, and with the help of stompClient we send this message to the “/app/send/message” route defined in the WebSocketController in Java as a value of @MessageMapping in onReceivedMessage method;

So, whenever the client send message to “/app/send/message” → this message at the same time is sent to all clients subscribed to the “/chat” channel.

This is how easy the work with Websockets in Java can be.

We have two browsers opened. Simulate two different clients. So, when in the left side browser user types message and press send button, this message should be send to both browsers, as each of them subscribed to the “/chat” channel.

And when right side browser send message in answer, the “Hi there, Client 1!” message appears in both browsers as well!

Conclusion

This is how it works! So, you can easily expand functionality and scale the project based on your needs, as much as possible. And now you know how easy is adding WebSocket messaging to the Spring Boot application.

Thank you! The source code available on my GitHub account:

As well you can find it on Oril Software GitHub.

#Java

#SpringBoot

Spring Boot + WebSockets + Angular 5

Hello guys! Here we will speak about how to set up Spring Boot project with Websocket messaging and Angular 5. As an output of this topic you will get small chat built with Spring Boot and Angular 5. Lets’s start First of all, we will set up Java project for this. The pom.xml file will […]

Ihor Kosandyak Avatar
Ihor Kosandyak

10 Nov, 2017 · 4 min read

Spring Boot With ChatGPT

ChatGPT stands out as one of the most robust language models available today. It’s capable of generating texts that closely resemble human-like conversation and can perform tasks such as translation and summarization, among other functionalities. This makes ChatGPT a preferred choice among developers and businesses seeking to enhance their AI capabilities. That’s why we’re here […]

Ihor Kosandyak Avatar
Ihor Kosandyak

28 Sep, 2023 · 4 min read

Spring Boot with Hazelcast

Have you ever faced with slow performance of your application? Have you ever thought of the way to boost your Spring app? If so — then this article is definitely for you. Here we will speak about using super powerful and leading in-memory data grid that may increase your app performance! So let’s jump into […]

Ihor Kosandyak Avatar
Ihor Kosandyak

5 Sep, 2018 · 4 min read