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. high stakes - low, single, single, single, etc. One of the advantages of playing online is that it will not hit the dealer cheat,


  4. How to download this application

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

  6. 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

  7. 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

  8. 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.


  9. pg slot สูตรลับ เทคนิคหรือสูตรลับแนวทางการเล่นสล็อต มีความง่ายๆ ไม่สลับซับซ้อน จาก pg slot สูตรลับ มีวิธีการเล่นที่มีระบบระเบียบแบบแผน พีจีสล็อต การเล่นเกมสล็อตให้สนุก นั้นต้องเล่นด้วยเงินจริง

  10. TubeDigger Crack + Keygen Free Download. TubeDigger Serial Key is a very quick processing tool as well. It is also the most effective time-saving device. TubeDigger License Key

  11. Microsoft Office 2016 Crack is the software package. It provides multiple tools like Word, Excel, PowerPoint, and Outlook applications.. MS Office 2016 Crack Key

  12. The Unexpected Moment Is Always Sweeter Words Quotes Inspirational Words Words. Thoughtful Surprise Gift Quote Gift Quotes Surprise Gifts Personalized Gifts.

  13. very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. Looking for the best English speaking course in Riyadh? Enhance your language skills with Ziyyara’s tailored online English classes in Saudi Arabia.
    For more info visit Spoken English Classes in Saudi Arabia or Call +971505593798

  14. These articles are published with great effort and are highly beneficial to know. I'm having a great time reading your blog. And positive remarks foster positive relationships. You're performing admirably. Keep going.
    B.Com Computers Colleges In Hyderabad

  15. reading this article was really interesting.I want to express my gratitude for all of your hard work in creating this fantastic essay. Searching for Riyadh's top English-speaking course? Improve your language abilities with customised online English courses Best Colleges in Hyderabad For BBA

  16. These papers are really helpful to know and are published with much effort. It's a pleasure to read your blog. Positive comments can help to build positive relationships. You're doing a great job. Proceed with caution.
    CA Classes in Hyderabad

  17. Anticipated to write you a very brief note to express my gratitude for your excellent suggestions that you have made here. In Velachery, we offer AngularJS training.
    Best Colleges For BBA In Hyderabad

  18. This comment has been removed by the author.

  19. Hi there, I'm quite glad I stumbled onto your webpage. Actually, I stumbled onto it by accident when searching Google for something else. Still, now that I'm here, I just wanted to say thanks for a great post and an all-around entertaining website. Please, keep up the wonderful work.CMA Coaching Institutes in Hyderabad