您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關websocket如何在springboot中應用,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
1.首先搭建一個簡單的springboot環境
<!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> </parent> <!-- Add typical dependencies for a web application --> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
2.引入springboot整合websocket依賴
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-websocket --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> <version>2.0.4.RELEASE</version> </dependency>
3.創建啟動springboot的核心類
package com; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class GlobalConfig { public static void main(String[] args) { SpringApplication.run(GlobalConfig.class, args); } }
4.創建websocket服務器
正如springboot 官網推薦的websocket案例,需要實現WebSocketHandler或者繼承TextWebSocketHandler/BinaryWebSocketHandler當中的任意一個.
package com.xiaoer.handler; import com.alibaba.fastjson.JSONObject; import org.springframework.web.socket.TextMessage; import org.springframework.web.socket.WebSocketSession; import org.springframework.web.socket.handler.TextWebSocketHandler; import java.util.HashMap; import java.util.Map; /** * 相當于controller的處理器 */ public class MyHandler extends TextWebSocketHandler { @Override protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception { String payload = message.getPayload(); Map<String, String> map = JSONObject.parseObject(payload, HashMap.class); System.out.println("=====接受到的數據"+map); session.sendMessage(new TextMessage("服務器返回收到的信息," + payload)); } }
5.注冊處理器
package com.xiaoer.config; import com.xiaoer.handler.MyHandler; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "myHandler/{ID}"); } public WebSocketHandler myHandler() { return new MyHandler(); } }
6.運行訪問
出現如上圖是因為不能直接通過http協議訪問,需要通過html5的ws://協議進行訪問.
7.創建Html5 客戶端
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <body> <input id="text" type="text" /> <button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button> <div id="message"> </div> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script> var userID="888"; var websocket=null; $(function(){ connectWebSocket(); }) //建立WebSocket連接 function connectWebSocket(){ console.log("開始..."); //建立webSocket連接 websocket = new WebSocket("ws://127.0.0.1:8080/myHandler/ID="+userID); //打開webSokcet連接時,回調該函數 websocket.onopen = function () { console.log("onpen"); } //關閉webSocket連接時,回調該函數 websocket.onclose = function () { //關閉連接 console.log("onclose"); } //接收信息 websocket.onmessage = function (msg) { console.log(msg.data); } } //發送消息 function send(){ var postValue={}; postValue.id=userID; postValue.message=$("#text").val(); websocket.send(JSON.stringify(postValue)); } //關閉連接 function closeWebSocket(){ if(websocket != null) { websocket.close(); } } </script> </body> </html>
8.運行
利用客戶端運行之后仍然會出現上圖中的一連接就中斷了websocket連接.
這是因為spring默認不接受跨域訪問:
As of Spring Framework 4.1.5, the default behavior for WebSocket and SockJS is to accept only same origin requests.
需要在WebSocketConfig中設置setAllowedOrigins.
package com.xiaoer.config; import com.xiaoer.handler.MyHandler; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.WebSocketHandler; import org.springframework.web.socket.config.annotation.EnableWebSocket; import org.springframework.web.socket.config.annotation.WebSocketConfigurer; import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry; @Configuration @EnableWebSocket public class WebSocketConfig implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(myHandler(), "myHandler/{ID}") .setAllowedOrigins("*"); } public WebSocketHandler myHandler() { return new MyHandler(); } }
如下圖,并未輸出中斷,說明連接成功.
9.服務器和客戶端的相互通信
服務器端收到消息
客戶端收到服務器主動推送消息
看完上述內容,你們對websocket如何在springboot中應用有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。