How to do it...

Let us create a simple messenger by performing the following steps:

  1. First, convert ch12-websocket to the Spring Boot 2.0 application by to pom.xml the Spring Boot 2.0.0.M2 starter POM dependencies, such as Spring WebFlux for Reactive components and Spring Boot actuator for project status monitoring and management.
  2. To add support for the websocket protocol, add the following starter POM dependency in pom.xml:
<dependency> 
   <groupId>org.springframework.boot</groupId> 
   <artifactId>spring-boot-starter-websocket</artifactId> 
</dependency> 
  1. To convert message payloads in JSON format to Java objects, add the following additional Maven dependency:
<dependency> 
      <groupId>com.google.code.gson</groupId> 
      <artifactId>gson</artifactId> 
</dependency> 
  1. Inside the core package org.packt.messaging.core, add the following typical Bootstrap class:
@SpringBootApplication 
public class ChatBootApplication { 
    
  public static void main(String[] args) throws Exception { 
      SpringApplication.run(ChatBootApplication.class,  
         args); 
    } 
}
  1. Inside srcmain esources, create an application.properties file that contains basic autoconfiguration details similar to the previous projects. No special properties for WebSocket support are needed to be registered here.
  2. Copy the config folder and logback.xml from the previous projects. Update the logger information of the logback.xml file.
  3. To manage the incoming payloads and outgoing messages, implement a custom handler inside the org.packt.messaging.core.config package through the org.springframework.web.socket.handler.TextWebSocketHandler API. This handler will utilize the Gson() utility to convert JSON payloads from the client to valid Java String objects. Moreover, this is the only @Component annotation where sessions are established per message received:
@Component 
public class HotlineSocketHandler extends TextWebSocketHandler { 
    
   List<WebSocketSession> sessions = new CopyOnWriteArrayList<>(); 
 
   @Override 
   public void handleTextMessage(WebSocketSession session,  
            TextMessage message) 
         throws InterruptedException, IOException { 
       
      for(WebSocketSession webSocketSession : sessions) { 
         Map value = new  
            Gson().fromJson(message.getPayload(),  
               Map.class); 
         String[] data =  
            value.get("data").toString().split(","); 
         webSocketSession.sendMessage( 
new TextMessage("Dear " +  
            data[0] + ", you complaint is now ...")); 
      } 
   } 
 
   @Override 
   public void afterConnectionEstablished( 
WebSocketSession session) throws Exception { 
         sessions.add(session); 
   } 
}
  1. This WebSocket messaging needs an endpoint that a client can be used to open message the communication channels. This endpoint is a unique URL mapped to one custom handler by the org.springframework.web.socket.config.annotation.WebSocketConfigurer class. This @Configuration class must enable WebSocket support in Spring Boot by applying the class-level annotation @EnableWebSocket:
@Configuration 
@EnableWebSocket 
public class ChatSocketConfig implements WebSocketConfigurer { 
 
   public void registerWebSocketHandlers( 
WebSocketHandlerRegistry registry) { 
      registry.addHandler(new HotlineSocketHandler(),  
         "/data"); 
   } 
} 
  1. At this point, we are finished configuring the server side of this application. It is time to set up the client side of the application by creating the required static resources needed to face the users. All these HTML, CSS, and JS files must be dropped inside a static folder, src/main/resources, in order for Spring Boot to auto recognize them:
  2. Now, inside the static folder, drop some HTML Bootstrap files (for example, bootstrap.min.css) for response web design, and jQuery JS files (for example, jquery-xxxx-min.js) for client-side socket implementation. Another option is to import these files from https://cdnjs.com/libraries/jquery/.
  3. Create an HTML 5 page, hotline.html, which will serve as the client of the application. It will contain form data needed to be sent through the WebSocket channels:
<!DOCTYPE html> 
<html> 
<head> 
    <title>Chapter 12</title> 
    <link href="./bootstrap.min.css" rel="stylesheet"> 
    <link href="./main.css" rel="stylesheet"> 
    <script src="./jquery-1.10.2.min.js"></script> 
</head> 
<body> 
        <div class="col-md-6"> 
            <form id="complaintForm" class="form-inline"> 
                <div class="form-group"> 
                   <label for="name">What is your name? 
</label> 
                    <input type="text" id="name"  
class="form-control"  
placeholder="Your name here..."> 
                    <label for="complaint"> 
What is your complaint? 
 </label> 
                    <input type="text" id="complaint"  
                      class="form-control"  
placeholder="Your complaint here..."> 
                </div> 
                <button id="send"  
class="btn btn-success"  
                  type="submit">Send</button> 
            </form> 
        </div> 
        <div class="row"> 
          <div class="col-md-12"> 
            <table id="helpdesk" class="table table-hover"> 
                <thead> 
                <tr> 
                    <th>Customer Service</th> 
                </tr> 
                </thead> 
                <tbody id="feedbacks"> 
                </tbody> 
            </table> 
        </div> 
    </div> 
</body> 
</html> 
Assign the necessary element ID to each of the form components.
  1. All the client-side WebSocket connections and transactions happen inside a JavaScript file. Using the jQuery API, create the following socketapp.js file, which implements some event handlers such as connect(), disconnect(), and sendFormData():
var ws; 
function setConnected(connected) { 
    $("#connect").prop("disabled", connected); 
    $("#disconnect").prop("disabled", !connected); 
    if (connected) { 
        $("#helpdesk").show(); 
    } 
    else { 
        $("#helpdesk").hide(); 
    } 
    $("#feedbacks").html(""); 
} 
 
function connect() { 
   ws = new WebSocket('ws://localhost:8085/ 
ch12-websocket/data'); 
   ws.onmessage = function(data){ 
      showFeedbacks(data.data); 
   } 
    setConnected(true); 
} 
 
function disconnect() { 
    if (ws != null) { 
        ws.close(); 
    } 
    setConnected(false); 
    console.log("Disconnected"); 
} 
 
function sendFormData() { 
   var data = JSON.stringify({'data': $("#name").val() +  
      "," + $("#complaint").val()}) 
   ws.send(data); 
} 
 
function showFeedbacks (message) { 
    $("#feedbacks").append("<tr><td><em> " + message +  
         "</em></td></tr>"); 
} 
 
$(function () { 
    $("form").on('submit', function (e) { 
        e.preventDefault(); 
    }); 
    $( "#connect" ).click(function() { connect(); }); 
    $( "#disconnect" ).click(function() { disconnect(); }); 
    $( "#send" ).click(function() { sendFormData(); }); 
}); 
  1. Import socketapps.js inside hotline.html using the <script> tag.
  2. Save all files. Clean, build, and deploy the Spring Boot application. Open a browser and execute http://localhost:8085/ch12-websocket/hotline.html:
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.145.107.100