Skip to main content

WebSocket + Spring boot web application example with source code download

In this article, we will show you how to develop a Simple Spring Boot web application with WebSocket
Why WebSocket?
We already know traditional HTTP requests are unidirectional and heavy.But WebSocket is bi-directional.The initial connection is using HTTP, then this connection gets upgraded to a socket-based connection. This single connection is then used for all future communication.The WebSocket message data exchange is much lighter compared to HTTP
Following technologies stack being used:

  • Spring Boot 2.1.4.RELEASE
  • Spring 5.1.6.RELEASE 
  • JDK 1.8
  • Eclipse Oxygen
  • Bootstrap
  • Thymeleaf
  • WebSocket

User Interface

Project Structure
Pom.xml[maven]
<?xml version="1.0" encoding="UTF-8"?>
<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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.1.4.RELEASE</version>
  <relativePath /> <!-- lookup parent from repository -->
 </parent>
 <artifactId>springboot-websocket-example</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>springboot-websocket-example</name>
 <properties>
  <java.version>1.8</java.version>
 </properties>
 <dependencies>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-thymeleaf</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
  </dependency>
  <dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-websocket</artifactId>
  </dependency>
  <dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20171018</version>
  </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
   </plugin>
  </plugins>
 </build>
 <groupId>com.knowledgefactory</groupId>
 <description>springboot-websocket-example</description>
</project>
SocketConfig.class
package com.knowledgefactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
@Configuration
@EnableWebSocket
public class SocketConfig implements WebSocketConfigurer {
 public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
  registry.addHandler(new TextHandler(), "/getMessage");
 }
}
TextHandler.class
package com.knowledgefactory;
import java.io.IOException;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class TextHandler extends TextWebSocketHandler {
  @Override
 public void handleTextMessage(WebSocketSession session, TextMessage message)
   throws InterruptedException, IOException, JSONException {
   String payload = message.getPayload();
  JSONObject jsonObject = new JSONObject(payload);
  session.sendMessage(new TextMessage("Your message:" + jsonObject.get("user")));
 }
}
KnowledgefactorydemoApplication.class(Spring Boot)
package com.knowledgefactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class KnowledgefactorydemoApplication {
 public static void main(String[] args) {
  SpringApplication.run(KnowledgefactorydemoApplication.class, args);
 }
}
index.html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat Application</title>
<link href="/bootstrap.min.css" rel="stylesheet">
<script src="/jquery.min.js"></script>
<script src="/main.js"></script>
<script src="/bootstrap.min.js"></script>
</head>
<body>
 <div class="container">
  <br> <br> <br>
  <div class="row">
   <div class="col-md-2"></div>
   <div class="col-md-8">
    <form class="form-inline">
     <div class="form-group">
      <label for="connect">Spring Boot socket programming
       example:</label>
      <button class="btn btn-success" id="connect" type="button">Start
      </button>
      <button class="btn btn-danger" id="disconnect" type="button"
       disabled="disabled">End</button>
     </div>
    </form>
   </div>
   <div class="col-md-2"></div>
  </div>
  <br> <br> <br>
  <div class="row">
   <div class="col-md-2">
    <table id="chat">
     <thead>
      <tr>
       <th>Welcome,Please enter your message</th>
      </tr>
     </thead>
    </table>
   </div>
   <div class="col-md-2"></div>
   <div class="col-md-6">
    <form>
     <div class="form-group">
      <textarea class="form-control" rows="5" id="user"
       placeholder="Write your message here..." required></textarea>
     </div>
     <button class="btn btn-primary" id="send" type="submit">Send</button>
    </form>
   </div>
   <div class="col-md-2"></div>
   <br> <br>
  </div>
  <div class="raw">
   <div class="col-md-2">
    <table id="response">
     <thead>
      <tr>
       <th>Your Message</th>
      </tr>
     </thead>
    </table>
   </div>
   <div class="col-md-2"></div>
   <div class="col-md-8">
    <form>
     <div class="form-group">
      <textarea id="helloworldmessage" class="form-control" rows="15"
       placeholder="Your Message" required></textarea>
     </div>
    </form>
   </div>
  </div>
 </div>
</body>
</html>
main.js
var ws;
function setConnected(connected) {
 $("#connect").prop("disabled", connected);
 $("#disconnect").prop("disabled", !connected);
}
function connect() {
 ws = new WebSocket('ws://localhost:8080/getMessage');
 ws.onmessage = function(data) {
  helloWorld(data.data);
 }
 setConnected(true);
}
function disconnect() {
 if (ws != null) {
  ws.close();
 }
 setConnected(false);
 console.log("Websocket is in disconnected state");
}
function sendData() {
 var data = JSON.stringify({
  'user' : $("#user").val()
 })
 ws.send(data);
}
function helloWorld(message) {
 $("#helloworldmessage").append("\n " + message + "");
}
$(function() {
 $("form").on('submit', function(e) {
  e.preventDefault();
 });
 $("#connect").click(function() {
  connect();
 });
 $("#disconnect").click(function() {
  disconnect();
 });
 $("#send").click(function() {
  sendData();
 });
});
Run
$ mvn spring-boot:run

Comments

Popular posts from this blog

Spring boot video streaming example-HTML5

This article shows you how to stream MP4 video in Spring Boot web application 
User Interface

Project Structure

Home Controller
@Controller
public class HomeController {
 @Autowired
 private MyResourceHttpRequestHandler handler;
 private final static File MP4_FILE = new File("D:\\videofiles\\video1.mp4");
 // supports byte-range requests
 @GetMapping("/index")
 public String home() {
  return "index";
 }
 // supports byte-range requests
 @GetMapping("/byterange")
 public void byterange( HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setAttribute(MyResourceHttpRequestHandler.ATTR_FILE, MP4_FILE);
  handler.handleRequest(request, response);
 }}
Spring Boot 
@SpringBootApplication
@ComponentScan({ "com" })
public class KnowledgefactorydemoApplication {
 public static void main(String[] args) {
  SpringApplication.run(KnowledgefactorydemoApplication.class, args);
 }}
MyResource HttpRequestHandler
@Componen…

DataTable-Pagination example with Spring boot,jQuery and ajax free download

This article shows you DataTable-Pagination example with Spring boot, jQuery and ajax. 

Following technologies stack being used:
Spring Boot 2.1.1.RELEASESpring 5.1.3.RELEASE Maven 3DatatablejQueryFree Markerjavascriptajax Project Structure
View(index.ftl) <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Knf|Pagination-Datatables</title> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="../../css/jquery.dataTables.min.css"> <body>  <section class="content">   <div class="container-fluid">    <table id="example" class="display" style="width: 100%">     <thead>      <tr>       <th>First name</th>       <th>La…

9 Best Job Posting Sites for Employee 2020-2022

One of the most common ways today’s job seekers uncover employment opportunities are by using online sources. There are hundreds of job boards, both generic and niche, as well as aggregators, social media channels, networking groups, and staffing company websites to choose from. The good news is they provide plenty of listings. The bad news is you can be easily overwhelmed by so many options. Here, knowledge factory offers 9 of what is generally considered the best job search websites around. There are many others, of course, but this list of best job search websites should give you a good starting point for your next job hunt: 1. LinkedIn
This top networking site allows you to find jobs through your extended network. User profiles serve as resumes. You can easily share career-related content and solicit or supply recommendations. Additionally, you can join groups, participate in conversations, and follow companies you find interesting and relevant to your job search. Premium pai…