SpringBoot集成WebSocket的兩種方式(JDK內置版和Spring封裝版)
本站在2014年4月時曾全面的學習HTML5的技術,特寫過HTML5的WebSocket示例,當時使用的Servlet3.0規(guī)范中的API,需要Tomcat7的支持(貌似在Tomcat6的后期維護版本也增加了WebSocket的支持),早在當初該示例還是本站的一個特色功能,好多來找我要源碼的呢。時隔多年再來使用SpringBoot架構來體驗一下集成WebSocket的實現(xiàn),經過一番資料的百科大概有找到使用兩種方式的實現(xiàn),我分別對它們進行了實踐,所以我稱這兩種方式為JDK內置版和Spring封裝版。
1.JDK內置版
主要是使用javax.websocket包下的注解進行集成,主要有:ServerEndpoint、OnOpen、OnMessage、OnClose、OnError相關的類和注解來集成,整體上比較簡單,都是基于注解定義的方法來聲明的,參考如下代碼所示:
JdkWebSocket
package cn.chendd.websocket.jdk;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
/**
* websocket實現(xiàn)
*
* @date 2023/6/2 21:02
*/
@Component
@ServerEndpoint(value = "/websocket/jdk")
public class JdkWebSocket {
@OnOpen
public void onOpen(Session session) {
System.out.println("WebSocketConfig.onOpen");
}
@OnMessage
public void onMessage(Session session , String message) {
System.out.println("WebSocketConfig.onMessage-->" + session + "--->" + message);
}
@OnClose
public void onClose() {
System.out.println("WebSocketConfig.onClose");
}
@OnError
public void onError(Session sesison , Throwable throwable) {
System.out.println("WebSocketConfig.onError-->" + sesison + "--->" + throwable);
}
}JdkWebSocketConfig
package cn.chendd.websocket.jdk;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @author chendd
* @date 2023/6/2 21:15
*/
@Configuration
public class JdkWebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}運行結果

2.Spring封裝版
Spring封裝版本有對于消息類型進行封裝,提供了更加全面的WebSocket方面的API,值得深入分析。
SpringWebSocketHandler
package cn.chendd.websocket.spring;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;
/**
* SpringWebSocketHandler
*
* @author chendd
* @date 2023/6/2 22:08
*/
@Component
public class SpringWebSocketHandler extends TextWebSocketHandler {
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
super.afterConnectionEstablished(session);
System.out.println("SpringWebSocketHandler.afterConnectionEstablished");
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
super.handleMessage(session, message);
System.out.println("SpringWebSocketHandler.handleMessage");
}
@Override
protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
super.handleTextMessage(session, message);
System.out.println("SpringWebSocketHandler.handleTextMessage");
}
@Override
protected void handlePongMessage(WebSocketSession session, PongMessage message) throws Exception {
super.handlePongMessage(session, message);
System.out.println("SpringWebSocketHandler.handlePongMessage");
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
super.handleTransportError(session, exception);
System.out.println("SpringWebSocketHandler.handleTransportError");
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
super.afterConnectionClosed(session, status);
System.out.println("SpringWebSocketHandler.afterConnectionClosed");
}
@Override
public boolean supportsPartialMessages() {
System.out.println("SpringWebSocketHandler.supportsPartialMessages");
return super.supportsPartialMessages();
}
}SpringWebSocketConfig
package cn.chendd.websocket.spring;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
import javax.annotation.Resource;
/**
* SpringWebSocketConfig
*
* @author chendd
* @date 2023/6/2 22:11
*/
@Configuration
@EnableWebSocket
public class SpringWebSocketConfig implements WebSocketConfigurer {
@Resource
private SpringWebSocketHandler springWebSocketHandler;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(springWebSocketHandler , "/websocket/spring").setAllowedOrigins("*");
}
}運行結果

3.其它說明
(1)本次示例重點在于服務端Java代碼的示例,未編寫前端示例,可在下方的項目源碼中參見前端的HTML集成,或者是使用本例中使用的在線WebSocket測試的頁面地址進行在線驗證,右鍵查看其源代碼也是原生的HTML5規(guī)范的相關代碼;
(2)提供了JDK的內置版本和Spring的封裝版本,個人推薦使用Spring的封裝版,畢竟JDK的注解不夠清晰的描述出被注解的方法的方法具體參數(shù),而Spring封裝版本有對于消息類型進行封裝;
(3)代碼比較簡單,結合前文的參考鏈接中的全量代碼也包含在內,代碼包結構如下:
參考文章鏈接:一個猜你所選的小程序隨寫

到此這篇關于SpringBoot集成WebSocket的兩種方式的文章就介紹到這了,更多相關SpringBoot集成WebSocket內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
基于Jenkins+Maven+Gitea+Nexus搭建CICD環(huán)境的方式
這篇文章主要介紹了基于Jenkins+Maven+Gitea+Nexus從0到1搭建CICD環(huán)境,大家都知道Nexus是一套“開箱即用”的系統(tǒng)不需要數(shù)據庫,它使用文件系統(tǒng)加Lucene來組織數(shù)據,需要的朋友可以參考下2022-01-01
Spring配置多個數(shù)據源并實現(xiàn)數(shù)據源的動態(tài)切換功能
這篇文章主要介紹了Spring配置多個數(shù)據源并實現(xiàn)數(shù)據源的動態(tài)切換功能,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01
spring+springmvc+mybatis 開發(fā)JAVA單體應用
這篇文章主要介紹了spring+springmvc+mybatis 開發(fā)JAVA單體應用的相關知識,本文通過圖文實例代碼的形式給大家介紹的非常詳細 ,需要的朋友可以參考下2018-11-11
使用Java橋接模式打破繼承束縛優(yōu)雅實現(xiàn)多維度變化
這篇文章主要為大家介紹了使用Java橋接模式打破繼承束縛,優(yōu)雅實現(xiàn)多維度變化,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-05-05

