一、引入依賴
| <!-- websocket推流--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
<!--thymeleaf模板--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
|
二、后端配置
1、新建一個 WebSocketStompConfig 類來實現 WebSocketMessageBrokerConfigurer
| //交給SpringBoot管理 @Configuration //注解開啟使用STOMP協議來傳輸基於代理(message broker)的消息 @EnableWebSocketMessageBroker @Order(1) public class WebSocketStompConfig implements WebSocketMessageBrokerConfigurer {
/** * 注冊stomp的端點(endpoint),並映射指定的url */ @Override public void registerStompEndpoints(StompEndpointRegistry registry) { /* 允許使用socketJs方式訪問,訪問點為webSocketServer,允許跨域 在網頁上我們就可以通過這個鏈接 http://localhost:8080/webSocket/server 來和服務器的WebSocket連接*/
//注冊一個STOMP的endpoint,並指定使用SockJS協議 registry.addEndpoint("/websocket/server").setAllowedOrigins("*").withSockJS(); }
/** * 配置信息代理 */ @Override public void configureMessageBroker(MessageBrokerRegistry registry) { // 訂閱Broker名稱 //兩個域上可以向客戶端發消息 registry.enableSimpleBroker("/queue", "/topic", "/user");
// 全局使用的消息前綴(客戶端訂閱路徑上會體現出來) //客戶端向服務端發送時的主題上面需要加"/app"作為前綴 // registry.setApplicationDestinationPrefixes("/app"); // 點對點使用的訂閱前綴(客戶端訂閱路徑上會體現出來),不設置的話,默認也是/user/ // registry.setUserDestinationPrefix("/user"); } |
三、后端向前端推流
1、創建Controller控制層
| @Slf4j @Controller @Api(tags = "webSocket推流") public class WebSocketRest{
//依賴messageTemplate發送模板 @Autowired private SimpMessagingTemplate messagingTemplate ;
/* * 跳轉webSocket測試頁面 * */ @GetMapping("webPage") @ApiOperation(value = "webPage 頁面跳轉") public String webPage(){ log.info("forward:web"); return "webscoket"; } } |
2、創建service服務層 (訂閱后)
| @Service public class WebSocketService { @Resource private SimpMessagingTemplate messagingTemplate ;
/* * 每隔1s向 "/topic/hello" 中 推送信息 * */ @Scheduled(fixedDelay = 1000) public String sendTest01(){ messagingTemplate.convertAndSend("/topic/hello",new ServerMessage("hello webSocket !!! >>> hello ")) ; return "message" ; } } |
3、編寫前端頁面
| <!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">貌似你的瀏覽器不支持websocket</h2> </noscript> <div> <div> <button id="hello" onclick="hello();">hello連接</button> <button id="disconnect" disabled="disabled" onclick="disconnect();">斷開連接</button> </div> </div> <script th:src="@{https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.5.0/sockjs.min.js}"></script> <script th:src="@{https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js}"></script> <script th:src="@{https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js}"></script> <script type="text/javascript"> var stompClient = null; function hello() { //若前后端分離,url要寫全,若在一個項目內,只寫/websocket/server就行 var url = "http://ip:8080/websocket/server" var socket = new SockJS(url); //鏈接SockJS 的endpoint 名稱為后台聲明的"/websocket/server" stompClient = Stomp.over(socket);//使用stomp子協議的WebSocket 客戶端 stompClient.connect({}, function(frame) {//鏈接Web Socket的服務端。 console.log('Connected: ' + frame); //廣播式發送,訂閱地址不需要加唯一標識;點對點發送,可自定義唯一標識 var subUrl= '/topic/hello'; stompClient.subscribe(subUrl, function(respnose){ //訂閱/topic/getResponse 目標發送的消息。這個是在控制器的@SendTo中定義的。 showResponse(JSON.parse(respnose.body).name); }); }); }
//斷開連接 function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); } </script> </body> </html> |
4、效果

五、前端向后端推送消息
1、創建Controller控制層
| @Slf4j @Controller @Api(tags = "webSocket推流") public class WebSocketRest{
//依賴messageTemplate發送模板 @Autowired private SimpMessagingTemplate messagingTemplate ;
/* * 跳轉webSocket測試頁面 * */ @GetMapping("webPage") @ApiOperation(value = "webPage 頁面跳轉") public String webPage(){ log.info("forward:web"); return "webscoket"; }
/* * 接收到 客戶端的消息 * */ @ResponseBody @MessageMapping(value = "/welcome") public void userChat(Message message) throws Exception { String url = "/topic/getResponse/"+message.getName(); messagingTemplate.convertAndSend(url, "welcome!"); } } |
2、編寫前端頁面
| <!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">貌似你的瀏覽器不支持websocket</h2></noscript> <div> <div> <!-- <button id="connect" onclick="connect();">connect連接</button>--> <button id="hello" onclick="hello();">hello連接</button> <button id="serverReturnMessage" onclick="serverReturnMessage();">serverReturnMessage連接</button> <button id="disconnect" disabled="disabled" 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> </div> <script th:src="@{https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.5.0/sockjs.min.js}"></script> <script th:src="@{https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js}"></script> <script th:src="@{https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js}"></script> <script type="text/javascript"> var stompClient = null;
function setConnected(flag) { // document.getElementById('connect').disabled = flag; document.getElementById('disconnect').disabled = !flag; document.getElementById('conversationDiv').style.visibility = flag ? 'visible' : 'hidden'; }
function serverReturnMessage() { //若前后端分離,url要寫全,若在一個項目內,只寫/websocket/server就行 var url = "http://ip:8080/websocket/server" var socket = new SockJS(url); //鏈接SockJS 的endpoint 名稱為后台聲明的"/websocket/server" stompClient = Stomp.over(socket);//使用stomp子協議的WebSocket 客戶端 stompClient.connect({}, function(frame) {//鏈接Web Socket的服務端。 setConnected(true); console.log('Connected: ' + frame); //廣播式發送,訂閱地址不需要加唯一標識;點對點發送,可自定義唯一標識 var subUrl= '/topic/serverReturnMessage'; stompClient.subscribe(subUrl, function(respnose){ //訂閱/topic/getResponse 目標發送的消息。這個是在控制器的@SendTo中定義的。 showResponse(JSON.parse(respnose.body).name); }); }); }
//斷開連接 function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); }
function showResponse(message) { var response = $("#response"); console.log(message); } //向stompClient發送請求 function sendName() { var name = $('#name').val(); //通過stompClient.send 向/welcome 目標 發送消息,這個是在控制器的@messageMapping 中定義的。 //在這里,可根據業務自定義json,甚至可以把訂閱地址的唯一標識在此傳入給后台解析 var obj = JSON.stringify({'name': name, 'retailmId': '001'})
stompClient.send("/sendTest", {}, obj); } </script> </body> </html> |
3、效果

六、點對點推流
1、修改WebSocketStompConfig配置文件。將標記行注釋取消。

2、創建服務層
| @Service public class WebSocketService { @Resource private SimpMessagingTemplate messagingTemplate ;
/* *點對點消息推送 * */ @Scheduled(fixedDelay = 1000) public void userChat() throws Exception { String url = "/user/nodeSendNode/"; String username = "zhangsan"; messagingTemplate.convertAndSendToUser(username, url ," 點 對 點 推送!"); } } |
3、編寫前端頁面
| <!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">貌似你的瀏覽器不支持websocket</h2></noscript> <div> <div> <button id="nodeSendNode" onclick="nodeSendNode();">nodeSendNode連接</button> <button id="disconnect" disabled="disabled" onclick="disconnect();">斷開連接</button> </div> </div> <script th:src="@{https://cdn.bootcdn.net/ajax/libs/sockjs-client/1.5.0/sockjs.min.js}"></script> <script th:src="@{https://cdn.bootcdn.net/ajax/libs/stomp.js/2.3.3/stomp.min.js}"></script> <script th:src="@{https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js}"></script> <!--<script th:src="@{sockjs.js}"></script> <script th:src="@{stomp.js}"></script> <script th:src="@{jquery.js}"></script>--> <script type="text/javascript"> var stompClient = null;
function setConnected(flag) { // document.getElementById('connect').disabled = flag; document.getElementById('disconnect').disabled = !flag; document.getElementById('conversationDiv').style.visibility = flag ? 'visible' : 'hidden'; }
//點對點 function nodeSendNode() { //配置用戶名 用於接收但對點消息 var username = 'zhangsan'; //若前后端分離,url要寫全,若在一個項目內,只寫/websocket/server就行 var url = "http://10.20.37.64:8080/websocket/server" var socket = new SockJS(url); //鏈接SockJS 的endpoint 名稱為后台聲明的"/websocket/server" stompClient = Stomp.over(socket);//使用stomp子協議的WebSocket 客戶端 stompClient.connect({}, function(frame) {//鏈接Web Socket的服務端。 setConnected(true); console.log('Connected: ' + frame); //點對點發送,訂閱地址不需要加唯一標識;點對點發送,可自定義唯一標識 var subUrl= '/user/nodeSendNode/'; //訂閱/topic/getResponse 目標發送的消息。這個是在控制器的@SendTo中定義的。 stompClient.subscribe('/user/'+ username +subUrl, function(respnose){ console.log(respnose.body); }); }); }
//斷開連接 function disconnect() { if (stompClient != null) { stompClient.disconnect(); } setConnected(false); console.log("Disconnected"); }
function showResponse(message) { var response = $("#response"); console.log(message); } </script> </body> </html> |
4、效果

