SpringBoot2.0整合WebSocket代碼實例
這篇文章主要介紹了SpringBoot2.0整合WebSocket代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
之前公司的某個系統(tǒng)為了實現推送技術,所用的技術都是Ajax輪詢,這種方式瀏覽器需要不斷的向服務器發(fā)出請求,顯然這樣會浪費很多的帶寬等資源,所以研究了下WebSocket,本文將詳細介紹下。
一、什么是WebSocket?
WebSocket是HTML5開始提供的一種在單個TCP連接上進行全雙工通訊的協議,能更好的節(jié)省服務器資源和帶寬,并且能夠更實時地進行通訊。
WebSocket 使得客戶端和服務器之間的數據交換變得更加簡單,允許服務端主動向客戶端推送數據,在WebSocket API中,瀏覽器和服務器只需要完成一次握手,兩者之間就直接可以創(chuàng)建持久性的連接,并進行雙向數據傳輸。
二、SpringBoot整合WebSocket
新建一個spring boot項目spring-boot-websocket,按照下面步驟操作。
pom.xml引入jar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
新建WebSocket的配置類
這個配置類檢測帶注解@ServerEndpoint的bean并注冊它們,配置類代碼如下:
@Configuration
public class WebSocketConfig {
/**
* 給spring容器注入這個ServerEndpointExporter對象
* 相當于xml:
* <beans>
* <bean id="serverEndpointExporter" class="org.springframework.web.socket.server.standard.ServerEndpointExporter"/>
* </beans>
* <p>
* 檢測所有帶有@serverEndpoint注解的bean并注冊他們。
*
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter() {
System.out.println("我被注入了");
return new ServerEndpointExporter();
}
}
新建WebSocket的處理類
這個處理類需要使用@ServerEndpoint,這個類里監(jiān)聽連接的建立關閉、消息的接收等,具體代碼如下:
@ServerEndpoint(value = "/ws/asset")
@Component
public class WebSocketServer {
@PostConstruct
public void init() {
System.out.println("websocket 加載");
}
private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
private static final AtomicInteger OnlineCount = new AtomicInteger(0);
// concurrent包的線程安全Set,用來存放每個客戶端對應的Session對象。
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<Session>();
/**
* 連接建立成功調用的方法
*/
@OnOpen
public void onOpen(Session session) {
SessionSet.add(session);
int cnt = OnlineCount.incrementAndGet(); // 在線數加1
log.info("有連接加入,當前連接數為:{}", cnt);
SendMessage(session, "連接成功");
}
/**
* 連接關閉調用的方法
*/
@OnClose
public void onClose(Session session) {
SessionSet.remove(session);
int cnt = OnlineCount.decrementAndGet();
log.info("有連接關閉,當前連接數為:{}", cnt);
}
/**
* 收到客戶端消息后調用的方法
*
* @param message
* 客戶端發(fā)送過來的消息
*/
@OnMessage
public void onMessage(String message, Session session) {
log.info("來自客戶端的消息:{}",message);
SendMessage(session, "收到消息,消息內容:"+message);
}
/**
* 出現錯誤
* @param session
* @param error
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("發(fā)生錯誤:{},Session ID: {}",error.getMessage(),session.getId());
error.printStackTrace();
}
/**
* 發(fā)送消息,實踐表明,每次瀏覽器刷新,session會發(fā)生變化。
* @param session
* @param message
*/
public static void SendMessage(Session session, String message) {
try {
// session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId()));
session.getBasicRemote().sendText(message);
} catch (IOException e) {
log.error("發(fā)送消息出錯:{}", e.getMessage());
e.printStackTrace();
}
}
/**
* 群發(fā)消息
* @param message
* @throws IOException
*/
public static void BroadCastInfo(String message) throws IOException {
for (Session session : SessionSet) {
if(session.isOpen()){
SendMessage(session, message);
}
}
}
/**
* 指定Session發(fā)送消息
* @param sessionId
* @param message
* @throws IOException
*/
public static void SendMessage(String message,String sessionId) throws IOException {
Session session = null;
for (Session s : SessionSet) {
if(s.getId().equals(sessionId)){
session = s;
break;
}
}
if(session!=null){
SendMessage(session, message);
}
else{
log.warn("沒有找到你指定ID的會話:{}",sessionId);
}
}
}
新建一個html
目前大部分瀏覽器支持WebSocket,比如Chrome, Mozilla,Opera和Safari,在html頁面進行websocket的連接建立、收消息的監(jiān)聽,頁面代碼如下:
<html>
<head>
<meta charset="UTF-8">
<title>websocket測試</title>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<style type="text/css">
h3,h4{
text-align:center;
}
</style>
</head>
<body>
<h3>WebSocket測試,客戶端接收到的消息如下:</h3>
<textarea id = "messageId" readonly="readonly" cols="150" rows="30" >
</textarea>
<script type="text/javascript">
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("遺憾:您的瀏覽器不支持WebSocket");
} else {
console.log("恭喜:您的瀏覽器支持WebSocket");
//實現化WebSocket對象
//指定要連接的服務器地址與端口建立連接
//注意ws、wss使用不同的端口。我使用自簽名的證書測試,
//無法使用wss,瀏覽器打開WebSocket時報錯
//ws對應http、wss對應https。
socket = new WebSocket("ws://localhost:8080/ws/asset");
//連接打開事件
socket.onopen = function() {
console.log("Socket 已打開");
socket.send("消息發(fā)送測試(From Client)");
};
//收到消息事件
socket.onmessage = function(msg) {
$("#messageId").append(msg.data+ "\n");
console.log(msg.data );
};
//連接關閉事件
socket.onclose = function() {
console.log("Socket已關閉");
};
//發(fā)生了錯誤事件
socket.onerror = function() {
alert("Socket發(fā)生了錯誤");
}
//窗口關閉時,關閉連接
window.unload=function() {
socket.close();
};
}
</script>
</body>
</html>
三、查看運行效果
啟動SpringBoot項目
打開首頁
本地瀏覽器打開首頁http://localhost:8080/,出現WebSocket測試頁面,同時后臺打印連接的日志。
有連接加入,當前連接數為:1,sessionId=0
往客戶端發(fā)送消息
通過上面日志可以看到客戶端連接連接的sessionId,我測試時候sessionId是0,然后瀏覽器訪問下面接口即可往客戶端發(fā)送消息。
//參數說明: id:sessionID //參數說明: message:消息內容 http://localhost:8080/api/ws/sendOne?id=0&message=你好Java碎碎念
發(fā)送消息動圖

到此SpringBoot整合WebSocket的功能已經全部實現,有問題歡迎留言溝通哦!
完整源碼地址: https://github.com/suisui2019/springboot-study
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Spring覆蓋容器中Bean的注解如何實現@OverrideBean
文章介紹了在項目開發(fā)中如何通過偷梁換柱的方式重寫Spring容器中的內置Bean,并指出了需要注意的兩點:1. 對應的Bean應基于接口注入;2. 如果不是基于接口注入,可以使用同包名同類名的方式重寫(可能存在潛在問題,不推薦),文章還強調了“基于接口編程”的好處2025-01-01
SpringBoot集成Mybatis-Plus多租戶架構實現
本文主要介紹了SpringBoot集成Mybatis-Plus多租戶架構實現,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
Java在Map轉Json字符串時出現"\"轉義字符的解決辦法
當一個Map被轉成Json字符串后,被添加到另一個Map中,會出現被加上“\”轉義字符的情況,這個時候該如何解決呢,下面就來和小編一起了解一下2023-07-07
IDEA關閉SpringBoot程序后仍然占用端口的排查與解決方法
在使用 IntelliJ IDEA 開發(fā) Spring Boot 應用時,有時即使關閉了應用,程序仍然占用端口,這會導致重新啟動應用時出現端口被占用的錯誤,所以本文給大家介紹了IDEA關閉SpringBoot程序后仍然占用端口的排查與解決方法,需要的朋友可以參考下2025-02-02

