By kswaughs | Tuesday, December 13, 2016

Spring Boot WebSocket Server push + AngularJS client

WebSocket is a very thin, lightweight layer above TCP used to build interactive web applications that send messages back and forth between a browser and the server.

The best examples are live updates websites, where once user access the website neither user nor browser sends request to the server to get the latest updates. Server only keeps sending the messages to the browser.

In this example, I am building a WebSocket application with Spring Boot using STOMP Messaging to provide the cricket live score updates for every 5 secs.

Step 1 : Maven setup

<project xmlns="" xmlns:xsi=""
    <description>Spring Boot WebSocket Application</description>
        <!-- Spring framework related jars -->

Step 2: Model class to hold the batsman & score details

public class Batsman {
    private String name;
    private int runs;
    private int balls;

    public String getName() {
        return name;

    public void setName(String name) { = name;

    public int getRuns() {
        return runs;

    public void setRuns(int runs) {
        this.runs = runs;

    public int getBalls() {
        return balls;

    public void setBalls(int balls) {
        this.balls = balls;

Step 3: Create a Web Socket & STOMP Messaging Configuration

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;

public class LiveScoreSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

    public void configureMessageBroker(MessageBrokerRegistry config) {

    public void registerStompEndpoints(StompEndpointRegistry registry) {
        registry.addEndpoint("/livescore-websocket").setAllowedOrigins("*"). withSockJS();


Step 4: Create a Message handling controller

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;


public class LiveCricketController {
    private LiveScoreService service;
    public List<Batsman> getScores() {
        List<Batsman> scoresList = service.getScore();
        return scoresList;

Step 5: Business Logic Implementation

Create a business logic component to get the live updates from back-end service. In this example, this class initializes the list of batsman objects with pre-filled data and later for every request, it will increments the runs & balls by 1 of any one batsman randomly.

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.springframework.stereotype.Component;


public class LiveScoreService {
    private List<Batsman> scoresList = initialScores();
    public List<Batsman> getScore() {

        Random rand = new Random();

        int randomNum = rand.nextInt((2 - 1) + 1);
        Batsman batsman = scoresList.get(randomNum);

        batsman.setBalls(batsman.getBalls() + 1);
        batsman.setRuns(batsman.getRuns() + 1);

        return scoresList;

    private List<Batsman> initialScores() {

        Batsman sachin = new Batsman();

        sachin.setName("Sachin Tendulkar");

        Batsman ganguly = new Batsman();
        ganguly.setName("Sourav Ganguly");

        List<Batsman> scoresList = new ArrayList<Batsman>();


        return scoresList;


Step 6: Scheduler Configuration

Configure a Scheduler task to send the updated scores to subscribed channel. The task is configured to run every 5 seconds.

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;


public class ScoreScheduler {
    private SimpMessagingTemplate template;
    LiveScoreService service;

    @Scheduled(fixedRate = 5000)
    public void publishUpdates(){
        template.convertAndSend("/topic/myscores", service.getScore());

Step 7 : Create a main class which will initialize and runs the spring boot application.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan({ "" })
public class BootApp {
    public static void main(String[] args) {
        Object[] { BootApp.class }, args);


Testing : AngularJS WebSocket Example

Now we will connect to this application from HTML Page using AngularJS Stomp component and display the live score updates. You can download ng-stomp.standalone.min.js from

<!DOCTYPE html>
<meta charset="UTF-8">
<title>WebSocket Client</title>
<script src=""></script>
<script src="ng-stomp.standalone.min.js"></script>
<script type="text/javascript">
  var app = angular.module('kswaughsLiveScore', ['ngStomp']);
  app.controller('LiveController', function ($stomp, $scope) {
      $scope.myres = [];
      $stomp.connect('http://localhost:8080/livescore-websocket', {})
            .then(function (frame) {
                var subscription = $stomp.subscribe('/topic/myscores', 
                    function (payload, headers, res) {
                        $scope.myres = payload;
                $stomp.send('/app/score', '');
    color : blue;

 list-style: none;
 padding:0px 0px 10px 0px;
<body >
<div class="liveScore" ng-app="kswaughsLiveScore" ng-controller="LiveController">
   <p>Cricket - Live Score</p>
        <li ng-repeat="x in myres">{{$index+1}} - {{}} - <b>{{x.runs}}</b> runs (<b>{{x.balls}}</b>balls)</li>


Cricket - Live Score

  • 1 - Sachin Tendulkar - 24 runs ( 26 balls)
  • 2 - Sourav Ganguly - 28 runs ( 30 balls)

The above scores gets updated every 5 secs when the server application runs.

Recommend this on


  1. How to keep every messages dequeue and enqueue from Apache ActiveMQ's topics in MySQL database using JMS?

  2. on which url its running, I tried to run on http://localhost:8080/livescore-websocket
    default message is coming "Welcome to SockJS!" ... on which url this application will run ?

    1. You have to run the client application. Here the client application is scores.html. Access 'scores.html' in any web browser which will connect to web socket application & displays the scores without browser refresh.

  3. Please click to play,if you wanna join casino online. Thank you
    gclub casino

  4. high stakes - low, single, single, single, etc. One of the advantages of playing online is that it will not hit the dealer cheat,


  5. How to download this application

  6. directly. It takes only 5-10 minutes, you can come to play or withdraw money to spend it. Online casinos are ready to

  7. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
    Angularjs course in chennai

  8. Pretty blog, so many ideas in a single site, thanks for the informative article, keep updating more article.
    hadoop training in chennai

    angularjs training in chennai

  9. Expected to form you a next to no word to thank you once more with respect to the decent recommendations you've contributed here. We are providing AngularJs training in velachery.
    For more details:AngularJs training in velachery

  10. Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
    Web Design Training

  11. Gclub Open for service via mobile phone All systems without the need to load extra programs to heavy machines Play as much as possible without minimum - open 24 hours a day, play and get rich with new playing techniques that come to update for members to use to play real money all the time Application is easy, just a few steps. Plus, you can plan your own play because you can play with no minimum through the modern live woven system. Apply today to receive many special promotions.


  12. Great Article. Thank you for sharing! Really an awesome post for every one.

    IEEE Final Year projects Project Centers in Chennai are consistently sought after. Final Year Students Projects take a shot at them to improve their aptitudes, while specialists like the enjoyment in interfering with innovation. For experts, it's an alternate ball game through and through. Smaller than expected IEEE Final Year project centers ground for all fragments of CSE & IT engineers hoping to assemble. Final Year Project Domains for IT It gives you tips and rules that is progressively critical to consider while choosing any final year project point.

    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai

  13. Great efforts put to publish these kinds of articles that are very useful to know. I’m thoroughly enjoying your blog. And Good comments create great relations. You’re doing an excellent job. Keep it up.

    Magento Development Training Course in Chennai Zuan Education

    Selenium Training Course in Chennai Zuan Education

  14. Nice blog, it’s so knowledgeable, informative, and good looking site. I appreciate your hard work. Good job. Thank you for this wonderful sharing with us. Keep Sharing.
    Digital Marketing Course In Kolkata