Please read tutorial https://www.jeejava.com/spring-boot-websocket-angularjs-gradle-example/

Gradle configuration

buildscript {
    ext {
        springBootVersion = '1.5.9.RELEASE'
    }

    repositories {
        mavenCentral()
    }

    dependencies {
        classpath "org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}"
    }
}

apply plugin: 'java'
apply plugin: 'org.springframework.boot'

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

configurations {
    all*.exclude module : 'spring-boot-starter-logging'
}

dependencies {
    compile("org.springframework.boot:spring-boot-starter-activemq")
    compile("org.springframework.boot:spring-boot-starter-websocket")
    //compile("com.h2database:h2")
    compile("org.apache.activemq:activemq-stomp")
    compile("io.projectreactor:reactor-net")
    compile("io.projectreactor:reactor-core")
    compile("io.netty:netty-all:4.1.2.Final")
    //logger slf4j
    compile("org.slf4j:slf4j-api:1.7.25")
    compile("org.slf4j:slf4j-log4j12:1.7.25")
    compile("commons-logging:commons-logging:1.2")
}

jar {
    baseName = 'SpringBootWebSocket'
    version = '0.0.1-SNAPSHOT'
    manifest {
        attributes("Main-Class": "com.jeejava.main.Application")
    }
}

Logger – log4j.properties

Put below log4j.properties file under src/main/resources

log4j.rootLogger=INFO, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= %d{dd-MM-yyyy hh:mm:ss,SSS} [%t] %-5p %c %x - %m%n

Change port in application.properties under src/main/resources

server.port=9999

WebSocket configuration class

package com.jeejava.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurationSupport;

@Configuration
@EnableWebSocket
public class WebSocketConfig extends WebSocketMessageBrokerConfigurationSupport {

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

	@Override
	public void configureMessageBroker(MessageBrokerRegistry config) {
		config.enableStompBrokerRelay("/topic").setRelayHost("localhost").setRelayPort(61613).setClientLogin("admin")
				.setClientPasscode("admin");
		config.setApplicationDestinationPrefixes("/app");
	}

}

Create model class – Message.java

package com.jeejava.model;

import java.io.Serializable;

public class Message implements Serializable {

	private static final long serialVersionUID = 8143497652802357639L;

	String msg;

	public Message(String msg) {
		this.msg = msg;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}
}

Configur scheduler for pushing updates every 5 seconds to topic

package com.jeejava.config;

import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import com.jeejava.model.Message;

@Configuration
@EnableScheduling
public class MqSchedulerConfig {

	private static final Logger LOGGER = LoggerFactory.getLogger(MqSchedulerConfig.class);

	@Autowired
	private SimpMessagingTemplate jmsTemplate;

	@Scheduled(fixedRate = 5000) // every 5 seconds
	public void publishUpdates() {
		String uuid = UUID.randomUUID().toString();

		LOGGER.info("Sending message: " + uuid);

		jmsTemplate.convertAndSend("/topic/msg", new Message(uuid));
	}

}

Create controller class

package com.jeejava.rest.controller;

import java.util.UUID;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.web.bind.annotation.RestController;

import com.jeejava.model.Message;

@RestController
public class MsgRestController {

	@MessageMapping("/hello")
	@SendTo("/topic/msg")
	public Message greeting() {
		return new Message(UUID.randomUUID().toString());
	}

}

Create main class

package com.jeejava.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {

	public static void main(String[] args) {
		SpringApplication.run(Application.class, args);
	}

}

Run the active mq broker

execute command from command prompt going to the directory <drive>\apache-activemq-5.15.3\bin\start activemq

Run the server application

Run the main class

Console output

21-02-2018 08:01:22,793 [reactor-tcp-io-8] INFO  reactor.io.net.impl.netty.tcp.NettyTcpClient  - CONNECTED: [id: 0x015370a7, L:/127.0.0.1:53107 - R:localhost/127.0.0.1:61613]
21-02-2018 08:01:23,021 [reactor-tcp-io-8] INFO  org.springframework.messaging.simp.stomp.StompBrokerRelayMessageHandler  - "System" session connected.
21-02-2018 08:01:23,023 [reactor-tcp-io-8] INFO  org.springframework.messaging.simp.stomp.StompBrokerRelayMessageHandler  - BrokerAvailabilityEvent[available=true, StompBrokerRelay[localhost:61613]]
21-02-2018 08:01:23,652 [pool-1-thread-1] INFO  com.jeejava.config.MqSchedulerConfig  - Sending message: 695b398b-4e6d-4feb-9632-7fff0699e7ad
21-02-2018 08:01:28,651 [pool-1-thread-1] INFO  com.jeejava.config.MqSchedulerConfig  - Sending message: 7d4cf575-8727-423d-8fa9-a0a41e2a09c8
21-02-2018 08:01:33,652 [pool-1-thread-1] INFO  com.jeejava.config.MqSchedulerConfig  - Sending message: f8908c89-462e-4a86-84c1-4b2aae40f2f3
Feb 21, 2018 8:01:36 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcherServlet'
21-02-2018 08:01:36,314 [http-nio-9999-exec-1] INFO  org.springframework.web.servlet.DispatcherServlet  - FrameworkServlet 'dispatcherServlet': initialization started
21-02-2018 08:01:36,336 [http-nio-9999-exec-1] INFO  org.springframework.web.servlet.DispatcherServlet  - FrameworkServlet 'dispatcherServlet': initialization completed in 22 ms
21-02-2018 08:01:38,651 [pool-1-thread-1] INFO  com.jeejava.config.MqSchedulerConfig  - Sending message: 7d454770-99f4-4bc7-a203-4d40db83b194
21-02-2018 08:01:43,652 [pool-1-thread-1] INFO  com.jeejava.config.MqSchedulerConfig  - Sending message: c48d856d-87fb-4210-b129-ccf2b34a0cfd
21-02-2018 08:01:48,652 [pool-1-thread-1] INFO  com.jeejava.config.MqSchedulerConfig  - Sending message: 9ca74ef9-2c3a-464a-a8f3-e0188140230c
21-02-2018 08:01:53,652 [pool-1-thread-1] INFO  com.jeejava.config.MqSchedulerConfig  - Sending message: 52139d5e-1a8a-47c8-9b1b-f27d530fb95c
21-02-2018 08:01:58,652 [pool-1-thread-1] INFO  com.jeejava.config.MqSchedulerConfig  - Sending message: 5a7d142f-450c-4bc9-978b-3ba037defef3
21-02-2018 08:02:01,948 [MessageBroker-2] INFO  org.springframework.web.socket.config.WebSocketMessageBrokerStats  - WebSocketSession[1 current WS(1)-HttpStream(0)-HttpPoll(0), 1 total, 0 closed abnormally (0 connect failure, 0 send limit, 0 transport error)], stompSubProtocol[processed CONNECT(1)-CONNECTED(1)-DISCONNECT(0)], stompBrokerRelay[2 sessions, localhost:61613 (available), processed CONNECT(2)-CONNECTED(2)-DISCONNECT(0)], inboundChannel[pool size = 8, active threads = 0, queued tasks = 0, completed tasks = 15], outboundChannelpool size = 8, active threads = 0, queued tasks = 0, completed tasks = 12], sockJsScheduler[pool size = 4, active threads = 1, queued tasks = 1, completed tasks = 5]
21-02-2018 08:02:03,653 [pool-1-thread-1] INFO  com.jeejava.config.MqSchedulerConfig  - Sending message: 45352338-753e-48d1-bcce-41643895da6d

Write the client code

<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Client with ActiveMQ Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src="ng-stomp.standalone.min.js"></script>
<script type="text/javascript">
  var app = angular.module('greetingMsg', ['ngStomp']);
  
  app.controller('MsgRestController', function ($stomp, $scope) { 
      $scope.myres = ""; 

      $stomp.connect('http://localhost:9999/message', {})
            .then(function (frame) {

				var subscription = $stomp.subscribe('/topic/msg',
					function (payload, headers, res) {                                                                                           
						$scope.myres = payload;
						$scope.$apply($scope.myres);
						console.log($scope.myres);
				});

				$stomp.send('/app/hello', '');
            });
  }); 
</script>
<style>
.msg {
    color : blue;
}

li {
	list-style: none;
	padding:0px 0px 10px 0px;
}
</style>
</head>
<body >
<div class="msg" ng-app="greetingMsg" ng-controller="MsgRestController">
   <p>Greeting Message - <b>{{myres.msg}}</b></p>
</div>
</body>
</html>

Run the client file

You will see the Greeting Message is updated with random string, which is randomly generated string from server side.

spring websocket activemq angularjs gradle

If you hit URL http://localhost:9999/message, you will get

Welcome to SockJS!

Above means WebSocket is running and ready to send message.

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on Roy Tutorials | TwitterFacebook Google PlusLinkedin | Reddit

Leave a Reply

Your email address will not be published. Required fields are marked *