Spring Boot learning continues. In the previous two blogs, we introduced how to use Spring Boot containers to build a web project and how to add HTTPS support to our Project. Based on these two articles, we will take a look at how to use WebSocket in Spring Boot today.
What is WebSocket
WebSocket provides duplex asynchronous communication function between the browser and the server, which means that we can use the browser to send messages to the server, and the server can also send messages to the browser. At present, the mainstream version of mainstream browsers supports WebSocket, but the workload of using WebSocket in actual development will be slightly larger, and the browser compatibility problem will be increased. At this time, we are more likely to use a sub-protocol of WebSocket to quickly implement our functions. OK, I won’t say much about WebSocket here, we mainly look at how to use it.
Project creation
Using WebSocket requires us to create a Project first. The creation method of this Project is the same as what we said in the previous article (I first learn about Spring Boot framework). The difference is that when choosing a dependency, we choose Thymeleaf and WebSocket dependencies, as shown in the figure below:
Configuring WebSocket
After the Project is successfully created, we first configure WebSocket and create the following class:
@Configuration@EnableWebSocketMessageBrokerpublic class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry stompEndpointRegistry) { stompEndpointRegistry.addEndpoint("/endpointSang").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic"); }}I'll say the following points about this category:
1@EnableWebSocketMessageBroker annotation means that the STOMP protocol is enabled to transmit proxy-based messages. Broker means proxy.
2. The registerStompEndpoints method represents the node that registers the STOMP protocol and specifies the mapped URL.
3.stompEndpointRegistry.addEndpoint("/endpointSang").withSockJS(); This line of code is used to register the STOMP protocol node and also specifies the use of the SockJS protocol.
4.configureMessageBroker method is used to configure the message broker. Since we implement the push function, the message broker here is /topic
Create a receiving class for the browser to send messages
Messages sent by the browser are received using this class:
public class RequestMessage { private String name; public String getName() { return name; }}Create a response message class
The message returned by the server to the browser is carried by this class:
public class ResponseMessage { private String responseMessage; public ResponseMessage(String responseMessage) { this.responseMessage = responseMessage; } public String getResponseMessage() { return responseMessage; }}Create a controller
@Controllerpublic class WsController { @MessageMapping("/welcome") @SendTo("/topic/getResponse") public ResponseMessage says(RequestMessage message) { System.out.println(message.getName()); return new ResponseMessage("welcome," + message.getName() + " !"); }}Regarding this controller, first of all, there is no need to say much about the @Controller annotation. The @MessageMapping annotation added on the say method is similar to the @RequestMapping we used before. The @SendTo annotation means that when the server has a message that needs to be pushed, a message will be sent to the browser subscribed to the path in @SendTo.
Add script
In this case, we need three js script files, namely the client script stomp.js of the STOMP protocol, the client script sock.js of SockJS and jQuery. These three js files are copied to the src/main/resources/static/js directory. OK, I have prepared these three js files for my friends. You can download the case directly at the end of the article. There are cases in the cases, or you can download these three js files by yourself.
Demo page
Before writing this HTML page, I want to first talk about what the effect we are trying to achieve is. After my Project is started, I access the message sending page in the browser and send a message on that page. When the server receives this message, a message is sent to all browsers connected to the server. OK, we create a new ws.html page in the src/main/resources/templates directory, with the following content:
<html lang="en" xmlns:th="http://www.thymeleaf.org"><head> <meta charset="UTF-8"/> <title>Broadcast WebSocket</title> <script th:src="@{js/sockjs.min.js}"></script> <script th:src="@{js/stomp.js}"></script> <script th:src="@{js/jquery-3.1.1.js}"></script></head><body onload="disconnect()"><noscript><h2 style="color: #e80b0a;">Sorry, the browser does not support WebSocket</h2></noscript><div> <div> <button id="connect" onclick="connect();">Connect</button> <button id="disconnect" disabled="disabled" onclick="disconnect();">Disconnect</button> </div> <div id="conversationDiv"> <label>Enter your name</label><input type="text" id="name"/> <button id="sendName" onclick="sendName();">Send</button> <p id="response"></p> </div></div><script type="text/javascript"> var stompClient = null; function setConnected(connected) { document.getElementById("connect").disabled = connected; document.getElementById("disconnect").disabled = !connected; document.getElementById("conversationDiv").style.visibility = connected ? 'visible' : 'hidden';// $("#connect").disabled = connected;// $("#disconnect").disabled = !connected; $("#response").html(); } function connect() { var socket = new SockJS('/endpointSang'); stompClient = Stomp.over(socket); stompClient.connect({}, function (frame) { setConnected(true); console.log('Connected:' + frame); stompClient.subscribe('/topic/getResponse', function (response) { showResponse(JSON.parse(response.body).responseMessage); }) }); } function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log('Disconnected'); } function sendName() { var name = $('#name').val(); console.log('name:' + name); stompClient.send("/welcome", {}, JSON.stringify({'name': name})); } function showResponse(message) { $("#response").html(message); }</script></body></html>Although there is a little more code here, it is very simple to analyze it carefully. First of all, I won’t talk about the part introduced by js file. If you don’t understand it here, you can refer to using Spring Boot to develop a web project. Then there are two buttons on our page, one is a connection and the other is a disconnection. The two buttons correspond to different click events. There is an input box below these two buttons, which is the content we want to send, and then there is a send button. The send button corresponds to a click event for sending a message. This is an element of the entire page, very simple. Let’s focus on the js logic code here.
The connect method is executed when I click the connection button. var socket = new SockJS('/endpointSang'); means that the endpoint name of the connected SockJS is /endpointSang, stompClient = Stomp.over(socket); means that using STOMP to create a WebSocket client. Then call the connect method in stompClient to connect to the server. After the connection is successful, call the setConnected method, which hides the hidden and displays the displayed. Then, by calling the subscribe method in stompClient to subscribe to the message sent by /topic/getResponse, that is, the parameter of the @SendTo annotation we added to the say method in Controller. The send method in stompClient means sending a message to the server, and the rest are all regular js usages. I won't repeat it.
Configure viewController
Next is to provide path maps for ws.html:
@Configurationpublic class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/ws").setViewName("/ws"); }}OK, after doing all this we can run the project. I open multiple browsers at the same time and send a message on one of them. Let's see the results:
I send messages on the top browser and both other browsers receive messages from me.
OK, the above is the entire process of using WebSocket to implement message push under the Spring Boot framework.
Download address of this case: demo
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.