springboot?使用websocket技術(shù)主動(dòng)給前端發(fā)送消息的實(shí)現(xiàn)
使用websocket技術(shù)主動(dòng)給前端發(fā)送消息
springBoot2.0對(duì)WebSocket的支持簡(jiǎn)直太棒了,直接就有包可以引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-websocket</artifactId> </dependency>
WebSocketConfig
啟用WebSocket的支持也是很簡(jiǎn)單
package com.spark.common.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.socket.server.standard.ServerEndpointExporter; /** * @Author Lxq * @Date 2021-06-12 17:11 * @Version 1.0 * 開(kāi)啟websocket支持 */ @Configuration public class WebSocketConfig { @Bean public ServerEndpointExporter serverEndpointExporter() { return new ServerEndpointExporter(); } }
WebSocketServer
這就是重點(diǎn)了,核心都在這里。
因?yàn)閃ebSocket是類(lèi)似客戶端服務(wù)端的形式(采用ws協(xié)議),那么這里的WebSocketServer其實(shí)就相當(dāng)于一個(gè)ws協(xié)議的Controller
直接@ServerEndpoint("/socketServer/{userId}") 、@Component啟用即可,然后在里面實(shí)現(xiàn)@OnOpen開(kāi)啟連接,@onClose關(guān)閉連接,@onMessage接收消息等方法。
新建一個(gè)ConcurrentHashMap webSocketMap 用于接收當(dāng)前userId的WebSocket,方便IM之間對(duì)userId進(jìn)行推送消息。單機(jī)版實(shí)現(xiàn)到這里就可以。
package com.spark.common.utils.websocket; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.spark.common.utils.StringUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import javax.websocket.*; import javax.websocket.server.PathParam; import javax.websocket.server.ServerEndpoint; import java.io.IOException; import java.util.concurrent.ConcurrentHashMap; /** * @Author Lxq * @Date 2021-06-12 17:13 * @Version 1.0 */ @ServerEndpoint("/socketServer/{userId}") @Component @Slf4j public class WebSocketServer { /** * 靜態(tài)變量,用來(lái)記錄當(dāng)前在線連接數(shù)。應(yīng)該把它設(shè)計(jì)成線程安全的。 */ private static int onlineCount = 0; /** * concurrent包的線程安全Set,用來(lái)存放每個(gè)客戶端對(duì)應(yīng)的MyWebSocket對(duì)象。 */ private static ConcurrentHashMap<String, WebSocketServer> webSocketMap = new ConcurrentHashMap<>(); /** * 與某個(gè)客戶端的連接會(huì)話,需要通過(guò)它來(lái)給客戶端發(fā)送數(shù)據(jù) */ private Session session; /** * 接收userId */ private String userId = ""; /** * 連接建立成功調(diào)用的方法 */ @OnOpen public void onOpen(Session session, @PathParam("userId") String userId) { this.session = session; this.userId = userId; if (webSocketMap.containsKey(userId)) { webSocketMap.remove(userId); webSocketMap.put(userId, this); //加入set中 } else { webSocketMap.put(userId, this); //加入set中 addOnlineCount(); //在線數(shù)加1 } log.info("用戶連接:" + userId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount()); try { sendMessage("連接成功"); } catch (IOException e) { log.error("用戶:" + userId + ",網(wǎng)絡(luò)異常!"); } } /** * 連接關(guān)閉調(diào)用的方法 */ @OnClose public void onClose() { if (webSocketMap.containsKey(userId)) { webSocketMap.remove(userId); //從set中刪除 subOnlineCount(); } log.info("用戶退出:" + userId + ",當(dāng)前在線人數(shù)為:" + getOnlineCount()); } /** * 收到客戶端消息后調(diào)用的方法 * * @param message 客戶端發(fā)送過(guò)來(lái)的消息 */ @OnMessage public void onMessage(String message, Session session) { log.info("用戶消息:" + userId + ",報(bào)文:" + message); //可以群發(fā)消息 //消息保存到數(shù)據(jù)庫(kù)、redis if (StringUtils.isNotBlank(message)) { try { //解析發(fā)送的報(bào)文 JSONObject jsonObject = JSON.parseObject(message); //追加發(fā)送人(防止串改) jsonObject.put("fromUserId", this.userId); String toUserId = jsonObject.getString("toUserId"); //傳送給對(duì)應(yīng)toUserId用戶的websocket if (StringUtils.isNotBlank(toUserId) && webSocketMap.containsKey(toUserId)) { webSocketMap.get(toUserId).sendMessage(jsonObject.toJSONString()); } else { log.error("請(qǐng)求的userId:" + toUserId + "不在該服務(wù)器上"); //否則不在這個(gè)服務(wù)器上,發(fā)送到mysql或者redis } } catch (Exception e) { e.printStackTrace(); } } } /** * @param session * @param error */ @OnError public void onError(Session session, Throwable error) { log.error("用戶錯(cuò)誤:" + this.userId + ",原因:" + error.getMessage()); error.printStackTrace(); } /** * 實(shí)現(xiàn)服務(wù)器主動(dòng)推送 */ public void sendMessage(String message) throws IOException { this.session.getBasicRemote().sendText(message); } /** * 發(fā)送自定義消息 */ public static void sendInfo(String message, @PathParam("userId") String userId) throws IOException { log.info("發(fā)送消息到:" + userId + ",報(bào)文:" + message); if (StringUtils.isNotBlank(userId) && webSocketMap.containsKey(userId)) { webSocketMap.get(userId).sendMessage(message); } else { log.error("用戶" + userId + ",不在線!"); } } /** * 獲取當(dāng)前在線人數(shù) * * @return */ public static synchronized int getOnlineCount() { return onlineCount; } /** * 添加人數(shù) */ public static synchronized void addOnlineCount() { WebSocketServer.onlineCount++; } /** * 減少人數(shù) */ public static synchronized void subOnlineCount() { WebSocketServer.onlineCount--; } }
websocket基礎(chǔ)入門(mén)-前端發(fā)送消息
項(xiàng)目結(jié)構(gòu)如下圖
TestSocket.java
package com.charles.socket; import javax.websocket.OnMessage; import javax.websocket.OnOpen; import javax.websocket.Session; import javax.websocket.server.ServerEndpoint; @ServerEndpoint(value = "/helloSocket") public class TestSocket { /*** * 當(dāng)建立鏈接時(shí),調(diào)用的方法. * @param session */ @OnOpen public void open(Session session) { System.out.println("開(kāi)始建立了鏈接..."); System.out.println("當(dāng)前session的id是:" + session.getId()); } /*** * 處理消息的方法. * @param session */ @OnMessage public void message(Session session, String data) { System.out.println("開(kāi)始處理消息..."); System.out.println("當(dāng)前session的id是:" + session.getId()); System.out.println("從前端頁(yè)面?zhèn)鬟^(guò)來(lái)的數(shù)據(jù)是:" + data); } }
index.jsp 代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Charles-WebSocket</title> <script type="text/javascript"> var websocket = null; var target = "ws://localhost:8080/websocket/helloSocket"; function buildConnection() { if('WebSocket' in window) { websocket = new WebSocket(target); } else if('MozWebSocket' in window) { websocket = MozWebSocket(target); } else { window.alert("瀏覽器不支持WebSocket"); } } // 往后臺(tái)服務(wù)器發(fā)送消息. function sendMessage() { var sendmsg = document.getElementById("sendMsg").value; console.log("發(fā)送的消息:" + sendmsg); // 發(fā)送至后臺(tái)服務(wù)器中. websocket.send(sendmsg); } </script> </head> <body> <button onclick="buildConnection();">開(kāi)始建立鏈接</button> <hr> <input id="sendMsg" /> <button onclick="sendMessage();">消息發(fā)送</button> </body> </html>
注意:
和后臺(tái)交互的時(shí)候,一定要先點(diǎn)擊:開(kāi)始建立連接。你懂的...沒(méi)有建立連接的話,是不能發(fā)送消息的。
先點(diǎn)擊,開(kāi)始建立連接,然后在文本框中輸入內(nèi)容:我是Charles,點(diǎn)擊消息發(fā)送,在看后臺(tái)日志。
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Java?Mybatis的初始化之Mapper.xml映射文件的詳解
這篇文章主要介紹了Java?Mybatis的初始化之Mapper.xml映射文件的詳解,解析完全局配置文件后接下來(lái)就是解析Mapper文件了,它是通過(guò)XMLMapperBuilder來(lái)進(jìn)行解析的2022-08-08Spring boot中PropertySource注解的使用方法詳解
這篇文章主要給大家介紹了關(guān)于Spring boot中PropertySource注解的使用方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12Struts2的配置 struts.xml Action詳解
這篇文章主要介紹了Struts2的配置 struts.xml Action詳解,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-10-10java實(shí)現(xiàn)漢字轉(zhuǎn)unicode與漢字轉(zhuǎn)16進(jìn)制實(shí)例
這篇文章主要介紹了java實(shí)現(xiàn)漢字轉(zhuǎn)unicode與漢字轉(zhuǎn)16進(jìn)制的實(shí)現(xiàn)方法,是Java操作漢字編碼轉(zhuǎn)換的一個(gè)典型應(yīng)用,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2014-10-10Java基于正則實(shí)現(xiàn)的日期校驗(yàn)功能示例
這篇文章主要介紹了Java基于正則實(shí)現(xiàn)的日期校驗(yàn)功能,涉及java文件讀取、日期轉(zhuǎn)換及字符串正則匹配相關(guān)操作技巧,需要的朋友可以參考下2017-03-03