Spring boot Learning is ongoing. Previous two blogs we've covered how to build a Web project using the Spring boot container (using spring boot to develop a Web project) and how to add HTTPS support for our project (using spring boot to develop a Web project (ii) Added HTTPS support), on the basis of these two articles, let's look at how to use WebSocket in spring boot today.
What is WebSocket
WebSocket provides a duplex asynchronous communication between the browser and the server, that is, we can use the browser to send messages to the server, the server can also send messages to the browser, the mainstream version of the mainstream browser to WebSocket support is relatively good, However, in the actual development of the use of websocket workload will be slightly larger, and increase the browser compatibility issues, this time we are more using a WebSocket sub-protocol stomp, use it to quickly implement our functions. OK, about WebSocket I will not say much here, we mainly see how to use, if the small partners are interested to see this answer to learn more about the WebSocket information websocket What is the principle? Why you can implement persistent connections.
Project creation
Using websocket requires that we create a project first, which is created in the same way as we did earlier (the Spring boot framework), and the difference is that you choose Thymeleaf and WebSocket dependencies when choosing dependencies, such as:
Configure WebSocket
After project creation is successful, let's first configure WebSocket and create the following classes:
@Configuration@EnableWebSocketMessageBroker Public class websocketconfig extends abstractwebsocketmessagebrokerconfigurer { @Override Public void registerstompendpoints(Stompendpointregistry stompendpointregistry) {Stompendpointregistry.addendpoint ("/endpointsang"). WITHSOCKJS (); }@Override Public void Configuremessagebroker(Messagebrokerregistry Registry) {Registry.enablesimplebroker ("/topic"); }}
For this class I say the following points:
The [email protected] annotation indicates that the broker is meant to be switched on using the STOMP Protocol to transfer agent-based messages.
The 2.registerStompEndpoints method represents the node that registers the STOMP protocol and specifies the URL of the map.
3. stompEndpointRegistry.addEndpoint("/endpointSang").withSockJS();
This line of code is used to register the Stomp Protocol node while specifying the use of the SOCKJS protocol.
The 4.configureMessageBroker method is used to configure the message agent, because we are implementing push function, here the message agent is/topic
Create a receive class where the browser sends a message
The message sent by the browser is received with this class:
publicclass RequestMessage { private String name; publicgetName() { return name; }}
Create a response message class
The message returned by the server to the browser is hosted by this class:
publicclass ResponseMessage { private String responseMessage; publicResponseMessage(String responseMessage) { this.responseMessage = responseMessage; } publicgetResponseMessage() { return responseMessage; }}
Create a Controller
@Controller public class wscontroller { @MessageMapping ( "/welcome" ) @SendTo ( "/topic/getresponse" ) public responsemessage say (Requestmessage message) {System.ou T.println (Message.getname ()); return new Responsemessage ( "welcome," + message.getname () + "!" ); }}
With respect to this controller, the first @controller annotations do not have to be much, the @messagemapping annotations added on the say method are similar to the @requestmapping we used earlier. @SendTo
annotations indicate that when a server has a message that needs to be pushed, a message is sent to the browser that subscribes to the path in @sendto.
Add a script
Our case requires three JS script files, namely the Stomp Protocol client script stomp.js, sockjs client Script sock.js, and jquery, these three JS files are copied to src/main/resources/static/ JS directory. OK, these three JS files I have been ready for the small partners, you can download the case directly at the end of the case, there are, you can download the three JS files yourself.
Demo page
Before I write this HTML page, I want to start by saying what the effect of our implementation looks like. When my project starts, the browser accesses the message sending page, sends a message on that page, and sends a message to all browsers connected to the server after the service receives the message. 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 Type 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, Browser does not support WebSocket</H2></noscript><div> <div> <button id="Connect" onclick="Connect ();" >Connection</button> <button id="Disconnect" disabled="Disabled" onclick= "Disconnect ();" >Disconnect Connection</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"> varStompclient =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() { varSocket =NewSOCKJS ('/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() { varName = $ (' #name '). Val (); Console.log (' Name: '+ name); Stompclient.send ("/welcome", {},JSON. stringify ({' name ': name}); } function showresponse(message) {$("#response"). HTML (message); }</script></body></html>
Although the code is slightly more, it is easy to analyze it carefully. First of all, the JS file introduced in the part I will no longer say, here if you do not understand the use of spring boot to develop a Web project. Then we have two buttons on the page, one is the connection, one is disconnected, two buttons correspond to different click events, under the two buttons there is an input box, is what we want to send the content, and then there is a Send button, send button corresponding to a send message click event. This is the entire page of elements, very simple, we focus here to look at the JS logic code. The Connect method is performed when I click the Connect button, and the var socket = new SockJS(‘/endpointSang‘);
endpoint name of the SOCKJS that represents the connection is called/endpointsang, which stompClient = Stomp.over(socket);
means that stomp is used to create the WebSocket client. Then call the Connect method in Stompclient to connect to the server, the connection succeeds after the setConnected
method is called, the hidden hidden, and the display is displayed. We then subscribe to the message sent by/topic/getresponse by calling the Subscribe method in Stompclient, which is the parameter of the @sendto annotation we added on the Say method in the controller. The Send method in stompclient indicates that a message is sent to the server, and the rest is the usual JS usage I will not repeat it.
Configure Viewcontroller
The next step is to provide path mappings for ws.html:
@Configurationpublicclass WebMvcConfig extends WebMvcConfigurerAdapter { @Override publicvoidaddViewControllers(ViewControllerRegistry registry) { registry.addViewController("/ws").setViewName("/ws"); }}
OK, after all this we can run the project, I open multiple browsers at the same time, and then send a message on one of them, and we'll look at the results:
I send a message on the top of the browser, and the other two browsers can receive my message.
OK, this is the whole process of using WebSocket to implement message pushes in the Spring boot framework.
This case:
This case GitHub address
Above.
Resources:
"The creator of Java EE development Spring Boot Combat" chapter seventh
Using WebSocket to implement message pushes under the Spring boot framework