Java后端向前端推送消息完整代碼實例
1、WebSocketConfig配置類
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
2、WebSocket消息發(fā)送接收
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
@ServerEndpoint(value = "/web/{id}")
public class WebSocketProcess {
/*
* 持有每個webSocket對象,以key-value存儲到線程安全ConcurrentHashMap,
*/
private static ConcurrentHashMap<Long, WebSocketProcess> concurrentHashMap = new ConcurrentHashMap<>(12);
/**
* 會話對象
**/
private Session session;
/*
* 客戶端創(chuàng)建連接時觸發(fā)
* */
@OnOpen
public void onOpen(Session session, @PathParam("id") long id) {
//每新建立一個連接,就把當(dāng)前客戶id為key,this為value存儲到map中
this.session = session;
concurrentHashMap.put(id, this);
log.info("Open a websocket. id={}", id);
}
/**
* 客戶端連接關(guān)閉時觸發(fā)
**/
@OnClose
public void onClose(Session session, @PathParam("id") long id) {
//客戶端連接關(guān)閉時,移除map中存儲的鍵值對
concurrentHashMap.remove(id);
log.info("close a websocket, concurrentHashMap remove sessionId= {}", id);
}
/**
* 接收到客戶端消息時觸發(fā)
*/
@OnMessage
public void onMessage(String message, @PathParam("id") String id) {
log.info("receive a message from client id={},msg={}", id, message);
}
/**
* 連接發(fā)生異常時候觸發(fā)
*/
@OnError
public void onError(Session session, Throwable error) {
log.error("Error while websocket. ", error);
}
/**
* 發(fā)送消息到指定客戶端
*
* @param id
* @param message
*/
public void sendMessage(long id, String message) throws Exception {
//根據(jù)id,從map中獲取存儲的webSocket對象
WebSocketProcess webSocketProcess = concurrentHashMap.get(id);
if (!ObjectUtils.isEmpty(webSocketProcess)) {
//當(dāng)客戶端是Open狀態(tài)時,才能發(fā)送消息
if (webSocketProcess.session.isOpen()) {
webSocketProcess.session.getBasicRemote().sendText(message);
} else {
log.error("websocket session={} is closed ", id);
}
} else {
log.error("websocket session={} is not exit ", id);
}
}
/**
* 發(fā)送消息到所有客戶端
*/
public void sendAllMessage(String msg) throws Exception {
log.info("online client count={}", concurrentHashMap.size());
Set<Map.Entry<Long, WebSocketProcess>> entries = concurrentHashMap.entrySet();
for (Map.Entry<Long, WebSocketProcess> entry : entries) {
Long cid = entry.getKey();
WebSocketProcess webSocketProcess = entry.getValue();
boolean sessionOpen = webSocketProcess.session.isOpen();
if (sessionOpen) {
webSocketProcess.session.getBasicRemote().sendText(msg);
} else {
log.info("cid={} is closed,ignore send text", cid);
}
}
}
}
3、消息推送Controller
import com.xyl.web.controller.common.WebSocketProcess;
import com.xyl.web.controller.common.WebSocketServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/testws")
public class WebSocketController {
/**
* 注入WebSocketProcess
**/
@Autowired
private WebSocketProcess webSocketProcess;
/**
* 向指定客戶端發(fā)消息
*
* @param id
*/
@PostMapping(value = "sendMsgToClientById")
public void sendMsgToClientById(@RequestParam long id, @RequestParam String text) {
try {
webSocketProcess.sendMessage(id, text);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 發(fā)消息到所有客戶端
*
* @param text
*/
@PostMapping(value = "sendMsgToAllClient")
public void sendMsgToAllClient(@RequestParam String text) {
try {
webSocketProcess.sendAllMessage(text);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 定時向客戶端推送消息
* @throws Exception
*/
@Scheduled(cron = "0/5 * * * * ?")
private void configureTasks() throws Exception {
webSocketProcess.sendAllMessage("向前端推送消息內(nèi)容");
}
}
4、測試HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>websocket測試</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="content"></div>
</body>
<script type="text/javascript">
$(function(){
var ws;
//檢測瀏覽器是否支持webSocket
if("WebSocket" in window){
$("#content").html("您的瀏覽器支持webSocket!");
//模擬產(chǎn)生clientID
let clientID = Math.ceil(Math.random()*100);
//創(chuàng)建 WebSocket 對象,注意請求路徑?。。。?
ws = new WebSocket("ws://127.0.0.1:9095/web/"+clientID);
//與服務(wù)端建立連接時觸發(fā)
ws.onopen = function(){
$("#content").append("<p>與服務(wù)端建立連接建立成功!您的客戶端ID="+clientID+"</p>");
//模擬發(fā)送數(shù)據(jù)到服務(wù)器
ws.send("你好服務(wù)端!我是客戶端 "+clientID);
}
//接收到服務(wù)端消息時觸發(fā)
ws.onmessage = function (evt) {
let received_msg = evt.data;
$("#content").append("<p>接收到服務(wù)端消息:"+received_msg+"</p>");
};
//服務(wù)端關(guān)閉連接時觸發(fā)
ws.onclose = function() {
console.error("連接已經(jīng)關(guān)閉.....")
};
}else{
$("#content").html("您的瀏覽器不支持webSocket!");
}
})
</script>
</html>
總結(jié)
到此這篇關(guān)于Java后端向前端推送消息完整代碼的文章就介紹到這了,更多相關(guān)Java后端向前端推送消息內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
10張圖總結(jié)出并發(fā)編程最佳學(xué)習(xí)路線
這篇文章主要介紹了并發(fā)編程的最佳學(xué)習(xí)路線,文中通過圖片介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-08-08
Java生成訂單號或唯一id的高并發(fā)方案(4種方法)
本文主要介紹了Java生成訂單號或唯一id的高并發(fā)方案,包括4種方法,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-01-01
Spring Cloud Config 使用本地配置文件方式
這篇文章主要介紹了Spring Cloud Config 使用本地配置文件方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-07-07
idea編輯XML文件出現(xiàn):Tag name expected報錯的解決
在XML中,一些特殊字符不能直接使用,因為它們被保留用于XML文檔的結(jié)構(gòu)和語法,如果直接使用這些保留字符,會導(dǎo)致解析錯誤,正確的做法是使用實體引用或字符引用,或者使用CDATA標(biāo)記將這些字符包裹起來2025-01-01
Java基礎(chǔ)之內(nèi)部類與代理知識總結(jié)
今天帶大家復(fù)習(xí)Java的基礎(chǔ)知識,文中有非常詳細(xì)的介紹及圖文示例,對正在學(xué)習(xí)Java的小伙伴們很有幫助,需要的朋友可以參考下2021-06-06
Java實現(xiàn)終止線程池中正在運行的定時任務(wù)
本篇文章給大家分享了JAVA中實現(xiàn)終止線程池中正在運行的定時任務(wù)的具體步驟和方法,有需要的朋友跟著學(xué)習(xí)下。2018-05-05
java.sql.Date和java.util.Date的區(qū)別詳解
Java中有兩個Date類,一個是java.util.Date通常情況下用它獲取當(dāng)前時間或構(gòu)造時間,另一個是java.sql.Date是針對SQL語句使用的,它只包含日期而沒有時間部分,這篇文章主要給大家介紹了關(guān)于java.sql.Date和java.util.Date區(qū)別的相關(guān)資料,需要的朋友可以參考下2023-03-03
Spring StateMachine實現(xiàn)狀態(tài)機使用示例詳解
本文介紹SpringStateMachine實現(xiàn)狀態(tài)機的步驟,包括依賴導(dǎo)入、枚舉定義、狀態(tài)轉(zhuǎn)移規(guī)則配置、上下文管理及服務(wù)調(diào)用示例,重點解析狀態(tài)同步、事件觸發(fā)與數(shù)據(jù)持久化機制,感興趣的朋友跟隨小編一起看看吧2025-07-07

