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

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.3.0.RELEASE</version>
    </parent>
    <groupId>com.kswaughs.spring</groupId>
    <artifactId>springboot-websocket</artifactId>
    <version>1.0</version>
    <name>springboot-websocket</name>
    <description>Spring Boot WebSocket Application</description>
    <dependencies>
        <!-- Spring framework related jars -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>1.3.0.RELEASE</version>
        </dependency>
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency> 
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

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

Batsman.java
package com.kswaughs.cricket.beans;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.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

LiveScoreSocketConfig.java
package com.kswaughs.cricket.config;

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;

@Configuration
@EnableWebSocketMessageBroker
public class LiveScoreSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {

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

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

}

Step 4: Create a Message handling controller

LiveCricketController.java
package com.kswaughs.cricket.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;

import com.kswaughs.cricket.beans.Batsman;
import com.kswaughs.cricket.service.LiveScoreService;

@Controller
public class LiveCricketController {
    
    @Autowired
    private LiveScoreService service;
    
    @MessageMapping("/score")
    @SendTo("/topic/myscores")
    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.

LiveScoreService.java
package com.kswaughs.cricket.service;

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

import org.springframework.stereotype.Component;

import com.kswaughs.cricket.beans.Batsman;

@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");
        sachin.setRuns(24);
        sachin.setBalls(26);

        Batsman ganguly = new Batsman();
        ganguly.setName("Sourav Ganguly");
        ganguly.setRuns(28);
        ganguly.setBalls(30);

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

        scoresList.add(sachin);
        scoresList.add(ganguly);

        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.

ScoreScheduler.java
package com.kswaughs.cricket.config;

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.kswaughs.cricket.service.LiveScoreService;

@Configuration
@EnableScheduling
public class ScoreScheduler {
        
    @Autowired
    private SimpMessagingTemplate template;
    
    @Autowired
    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.

BootApp.java
package com.kswaughs.cricket.config;

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

@SpringBootApplication
@ComponentScan({ "com.kswaughs.cricket" })
public class BootApp {
    
    public static void main(String[] args) {
        
        SpringApplication.run(new 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 https://github.com/beevelop/ng-stomp.

scores.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Client</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('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;
                        $scope.$apply($scope.myres);
                });
            
                $stomp.send('/app/score', '');
         });
  });
  
 </script>
 <style> 
 .liveScore{
    color : blue;
 }

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

Output

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


27 comments:

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

    ReplyDelete
  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 ?

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

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

    maxbet

    ReplyDelete
  4. How to download this application

    ReplyDelete
  5. directly. It takes only 5-10 minutes, you can come to play or withdraw money to spend it. Online casinos are ready to
    จีคลับ

    ReplyDelete
  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

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

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

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

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

    จีคลับ

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

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

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

    ReplyDelete