First of all, Websocket is a persistent protocol, compared to HTTP, which is a non-persistent protocol.
Let's take a simple example and explain it with the widely used PHP life cycle.
1) The life cycle of HTTP is defined by Request, that is, a Request and a Response, then in HTTP 1.0, this HTTP request is over.
Improvements have been made in HTTP 1.1, so that there is a keep-alive , that is, in one HTTP connection, multiple Requests can be sent and multiple Responses can be received.
But remember Request = Response, which is always the case in HTTP, which means that a request can only have one response. And this response is also passive and cannot be initiated actively.
2. Enable websocket support (@EnableWebSocketMessageBroker)
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; /** (1) The @EnableWebSocketMessageBroker annotation is used to enable the use of the STOMP protocol to transmit messages based on the broker (MessageBroker), at this time the controller (controller) Started supporting @MessageMapping just like using @requestMapping. (2) Register a Stomp node (endpoint) and specify the use of the SockJS protocol. (3) Configure the message broker (MessageBroker). **/ @Configuration @EnableWebSocketMessageBroker//1 public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/endpointWisely").withSockJS(); //2 } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.enableSimpleBroker("/topic");//3 } }
3. Actions similar to controller requests
import org.springframework.messaging.handler.annotation.MessageMapping; import org.springframework.messaging.handler.annotation.SendTo; import org.springframework.stereotype.Controller; /** * *(1) @MessageMapping and @RequestMapping have similar functions. They are used to set the URL mapping address. When the browser initiates a request to the server, it needs to pass this address. * *(2) If the server receives the message, it will send the message to the address in the brackets subscribed to @SendTo. * @author lanwx *@time Nov 22, 2017 10:11:37 AM */ @Controller public class WsController { @MessageMapping("/welcome") // 1 address that accepts requests @SendTo("/topic/getResponse") // 2 subscribed address public WiselyResponse say(WiselyMessage message) throws Exception { return new WiselyResponse("Welcome, " + message.getName() + "!"); } }
4. Pages
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8" /> <title>Spring Boot+WebSocket+广播式</title> </head> <body onload="disconnect()"> <noscript><h2 style="color: #ff0000">It looks like your browser does not support websocket</h2></noscript> <div> <div> <button id="connect" onclick="connect();">连接</button> <button id="disconnect" disabled="disabled" onclick="disconnect();">断开连接</button> </div> <div id="conversationDiv"> <label>Enter your name</label><input type="text" id="name" /> <button id="sendName" onclick="sendName();">发送</button> <p id="response"></p> </div> </div> <script src="https://cdn.bootcss.com/angular.js/1.5.6/angular.min.js"></script> <script src="https://cdn.bootcss.com/sockjs-client/1.1.4/sockjs.min.js"></script> <script src="https://cdn.bootcss.com/stomp.js/2.3.3/stomp.min.js"></script> <script src="/common/jquery/3.2.1/jquery-3.2.1.js"></script> <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'; $('#response').html(); } function connect() { // Register to a Stomp node var socket = new SockJS('/endpointWisely'); //1 stompClient = Stomp.over(socket);//2 stompClient.connect({}, function(frame) {//3 setConnected(true); console.log('Start connecting Connected: ' + frame); stompClient.subscribe('/topic/getResponse', function(respnose){ //4 showResponse(JSON.parse(respnose.body).responseMessage); }); }); } function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); } // Send to the address @MessageMapping("/welcome") function sendName() { var name = $('#name').val(); stompClient.send("/welcome", {}, JSON.stringify({ 'name': name }));//5 } function showResponse(message) { var response = $("#response"); response.html(message); } </script> </body> </html>