戰鬥前準備:新建Spring Boot專案選擇Thymeleaf和WebSocket依賴
設定WebSocket.需要在設定類上使用@EnableWebSocketMessageBroker開啟WebSocket支援,並實現WebSocketMessageBrokerConfigurer介面,重寫方法來設定WebSocket
(SpringBoot顛覆者裡是繼承AbstractWebSocketMessageBrokerConfigurer 類,但是那個類已經過時了)
import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;
/**
* 第一步,設定WebSocket.需要在設定類上使用@EnableWebSocketMessageBroker開啟WebSocket支援
* 並實現WebSocketMessageBrokerConfigurer介面
* 重寫方法來設定WebSocket
*/
@Configuration
//通過@EnableWebSocketMessageBroker註解開啟使用STOMP協定在傳輸基於代理(message broker)的訊息
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
//註冊STOMP協定的節點(endpoint),並對映指定的URL
public void registerStompEndpoints(StompEndpointRegistry registry){
//註冊一個STOMP的endpoint,並指定使用SockJS協定
registry.addEndpoint("/endpointWisely").withSockJS();
}
//設定訊息代理(Message Broker)
public void configureMessageBroker(MessageBrokerRegistry registry){
//廣播式設定一個/topic訊息代理
registry.enableSimpleBroker("/topic");
}
}
//瀏覽器向伺服器端傳送的訊息用此類接收
public class WiselyMessage {
public String name;
public String getName(){
return name;
}
}
//伺服器端向瀏覽器傳送的此類的訊息
public class WiselyResponse {
private String responseMessage;
public WiselyResponse(String responseMessage){
this.responseMessage = responseMessage;
}
public String getResponseMessage() {
return responseMessage;
}
}
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
import test.demo4.domain.WiselyMessage;
import test.demo4.domain.WiselyResponse;
@Controller
public class WsController {
//當瀏覽器向伺服器端傳送請求時,通過@MessageMapping對映/welcome這個地址,類似於@RequestMapping
@MessageMapping("/welcome")
//當伺服器端有訊息時,會訂閱了@SendTo中的路徑的瀏覽器傳送訊息
@SendTo("/topic/getResponse")
public WiselyResponse say(WiselyMessage message)throws Exception{
Thread.sleep(3000);
return new WiselyResponse("Welcome "+message.getName()+" !");
}
}
將stomp.min.js、scokjs.min.js和jquery.js放置在src/main/resources/static下
找資源太難的話,當然已經為你們準備好啦!
連結失效的話後臺私信我哦!
連結:https://pan.baidu.com/s/1UsP-4w1OkTUiz_YvVgFlVQ
提取碼:9wpf
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring Boot+WebSoc+廣播式</title>
</head>
<body onload="disconnect()">
<noscript><h2 style="color: #ff0000">貌似瀏覽器不支援WebSocket</h2></noscript>
<div>
<div>
<button id="connect" onclick="connect();">連線</button>
<button id="disconnect" onclick="disconnect();">斷開連線</button>
</div>
<div id="conversationDiv">
<label>輸入你的名字</label><input type="text" id="name"/>
<button id="sendName" onclick="sendName();">傳送</button>
<p id="response"></p>
</div>
<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.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() {
//連線SockJS的endpoint名稱為"/endpointWisely"
var socket = new SockJS('/endpointWisely');
//使用STOMP子協定的WebSocket使用者端
stompClient = Stomp.over(socket);
//連線WebSocket伺服器端
stompClient.connect({},function (frame) {
setConnected(true);
console.log('Connected:'+frame);
//通過stompClient.subscribe訂閱/topic/getResponse目標(destination)傳送訊息
//這個是在控制器的@SendTo中定義的
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();
//通過stompClient.send向/welcome目標(destination)傳送訊息
//這個是在控制器的@MessageMapping中定義的
stompClient.send("/welcome",{},JSON.stringify({"name":name}));
}
function showResponse(message) {
var response = $("#response");
response.html(message);
}
</script>
</div>
</body>
</html>
為ws.html提供便捷的路徑對映
將所有/static/** 存取都對映到classpath:/static/ 目錄下
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
//為ws.html提供便捷的路徑對映
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/ws").setViewName("/ws");
}
//將所有/static/** 存取都對映到classpath:/static/ 目錄下
public void addResourceHandlers(ResourceHandlerRegistry registry) {
System.out.println("==========靜態資源攔截!============");
registry.addResourceHandler("/static/**/").addResourceLocations("classpath:/static/");
}
}
跑跑跑起來…
ps:以上內容參考SpringBoot顛覆者,學習筆記,僅供參考