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="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
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
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
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.
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.
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.
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.
<!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.
How to keep every messages dequeue and enqueue from Apache ActiveMQ's topics in MySQL database using JMS?
ReplyDeleteGreat Article
DeleteB.Tech Final Year Projects for CSE in Angularjs
Project Centers in Chennai
JavaScript Training in Chennai
JavaScript Training in Chennai
Thanks for your sharing
Deletefifa55
sbobet
gclub
บาคาร่า
on which url its running, I tried to run on http://localhost:8080/livescore-websocket
ReplyDeletedefault message is coming "Welcome to SockJS!" ... on which url this application will run ?
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.
Deletehigh stakes - low, single, single, single, etc. One of the advantages of playing online is that it will not hit the dealer cheat,
ReplyDeletemaxbet
How to download this application
ReplyDeletedirectly. It takes only 5-10 minutes, you can come to play or withdraw money to spend it. Online casinos are ready to
ReplyDeleteจีคลับ
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
ReplyDeleteAngularjs course in chennai
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.
ReplyDeleteFor more details:AngularJs training in velachery
The post you wrote which is full of informative content. I Like it very much. Keep on posting!!
ReplyDeletePHP Training in Chennai
PHP Course in Chennai
Python Training in Chennai
Java Training in Chennai
Software Testing Training in Chennai
PHP Training in Annanagar
PHP Training in Tambaram
Your article inspired me more and keep writing.
ReplyDeleteSalesforce Training in Chennai
Big Data Training in Chennai
Android Training in Chennai
Selenium Training in Chennai
JAVA Training in Chennai
German Classes in chennai
Best JAVA Training institute in Chennai
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จีคลับ
Thank you much more for sharing the innovative post. This post is very creative and very interesting. well done...!
ReplyDeletePega Training in Chennai
Pega Developer Training
Linux Training in Chennai
Tableau Training in Chennai
Spark Training in Chennai
Excel Training in Chennai
Corporate Training in Chennai
Oracle Training in Chennai
Oracle DBA Training in Chennai
Social Media Marketing Courses in Chennai
Admire this blog. Keep sharing more updates like this
ReplyDeleteEthical Hacking Course in Chennai
Ethical hacking course in bangalore
Ethical hacking course in coimbatore
Hacking course in bangalore
Ethical hacking in bangalore
Ethical hacking training in bangalore
Ethical Hacking institute in Bangalore
Ethical hacking Training institute in bangalore
Tally Course in Bangalore
German Classes in Bangalore
I liked this blog.. I got some clear information from this blog.. Thanks for taking a time to share this blog...
ReplyDeleteData Science Course in Chennai
Data Science Courses in Bangalore
Data Science Course in Coimbatore
Data Science Course in Hyderabad
Data Science Institute in Marathahalli
Data Science Training in Bangalore
Best Data Science Courses in Bangalore
Data Science Institute in Bangalore
Spoken English Classes in Bangalore
DevOps Training in Bangalore
Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information.
ReplyDeleteCyber Security Training Course in Chennai | Certification | Cyber Security Online Training Course | Ethical Hacking Training Course in Chennai | Certification | Ethical Hacking Online Training Course | CCNA Training Course in Chennai | Certification | CCNA Online Training Course | RPA Robotic Process Automation Training Course in Chennai | Certification | RPA Training Course Chennai | SEO Training in Chennai | Certification | SEO Online Training Course
Thanks for sharing this blog. It was so informative.
ReplyDeleteNon technical IT jobs
Tech jobs for non techies
pg slot สูตรลับ เทคนิคหรือสูตรลับแนวทางการเล่นสล็อต มีความง่ายๆ ไม่สลับซับซ้อน จาก pg slot สูตรลับ มีวิธีการเล่นที่มีระบบระเบียบแบบแผน พีจีสล็อต การเล่นเกมสล็อตให้สนุก นั้นต้องเล่นด้วยเงินจริง
ReplyDeleteTubeDigger 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
ReplyDeleteMicrosoft Office 2016 Crack is the software package. It provides multiple tools like Word, Excel, PowerPoint, and Outlook applications.. MS Office 2016 Crack Key
ReplyDeleteThe Unexpected Moment Is Always Sweeter Words Quotes Inspirational Words Words. Thoughtful Surprise Gift Quote Gift Quotes Surprise Gifts Personalized Gifts. https://wishesquotz.com/surprise-quotes-for-him/
ReplyDeletevery 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.
ReplyDeleteFor more info visit Spoken English Classes in Saudi Arabia or Call +971505593798
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.
ReplyDeleteB.Com Computers Colleges In Hyderabad
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
ReplyDeleteThese 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.
ReplyDeleteCA Classes in Hyderabad
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.
ReplyDeleteBest Colleges For BBA In Hyderabad
This comment has been removed by the author.
ReplyDeleteHi 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
ReplyDelete