WebSocket實(shí)現(xiàn)數(shù)據(jù)庫(kù)更新時(shí)前端頁(yè)面刷新
本文實(shí)例為大家分享了WebSocket實(shí)現(xiàn)數(shù)據(jù)庫(kù)更新時(shí)前端頁(yè)面刷新,供大家參考,具體內(nèi)容如下
后臺(tái)代碼:
WebSocketConfig:
package com.x.common.websocket;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
WebSocketServlet:
package com.x.common.websocket;
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket/{userId}")
@Component
public class WebSocketServlet {
private static int onlineCount = 0;
private static Map<String, WebSocketServlet> clients = new ConcurrentHashMap<>();
private Session session;
private String userId;
@OnOpen
public void onOpen(@PathParam("userId") String userId, Session session) throws IOException {
this.userId = userId;
this.session = session;
addOnlineCount();
clients.put(userId, this);
System.out.println("已連接");
}
@OnClose
public void onClose() throws IOException {
clients.remove(userId);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
JSONObject jsonTo = JSONObject.parseObject(message);
if (!jsonTo.get("To").equals("All")){
sendMessageTo("給一個(gè)人", jsonTo.get("To").toString());
}else{
sendMessageAll("給所有人");
}
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public void sendMessageTo(String message, String To) throws IOException {
// session.getBasicRemote().sendText(message);
//session.getAsyncRemote().sendText(message);
for (WebSocketServlet item : clients.values()) {
if (item.userId.equals(To) ){
item.session.getAsyncRemote().sendText(message);
}
}
}
public void sendMessageAll(String message) throws IOException {
for (WebSocketServlet item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocketServlet.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocketServlet.onlineCount--;
}
public static synchronized Map<String, WebSocketServlet> getClients() {
return clients;
}
}
JS代碼:
var websocket = null;
//判斷當(dāng)前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8086/websocket/1");
} else {
alert('當(dāng)前瀏覽器 Not support websocket')
}
//連接發(fā)生錯(cuò)誤的回調(diào)方法
websocket.onerror = function() {
console.log("WebSocket連接發(fā)生錯(cuò)誤");
};
//連接成功建立的回調(diào)方法
websocket.onopen = function() {
console.log("WebSocket連接成功");
}
//接收到消息的回調(diào)方法
websocket.onmessage = function(event) {
//返回?cái)?shù)據(jù)轉(zhuǎn)JSON
var json=JSON.parse(event.data);
//result為bootstrap table 返回?cái)?shù)據(jù)
var rows=result.rows;
for(var i=0;i<rows.length;i++){
var row=rows[i];
if(row.id==json.id){
//判斷列Id相同時(shí)刷新表格
//$('#dataGrid').bootstrapTable('updateByUniqueId', {index: i, row: row});'refresh'
$('#dataGrid').bootstrapTable('refresh');
}
}
console.log(event.data);
}
//連接關(guān)閉的回調(diào)方法
websocket.onclose = function() {
console.log("WebSocket連接關(guān)閉");
}
//監(jiān)聽窗口關(guān)閉事件,當(dāng)窗口關(guān)閉時(shí),主動(dòng)去關(guān)閉websocket連接,防止連接還沒斷開就關(guān)閉窗口,server端會(huì)拋異常。
window.onbeforeunload = function() {
closeWebSocket();
}
//關(guān)閉WebSocket連接
function closeWebSocket() {
websocket.close();
}
返回前臺(tái)是調(diào)用方法:
@Autowired
private WebSocketServlet scoket;
//學(xué)生信息
XStudentInfoEntity student = xStudentInfoService.getObjectById(id.replace("\"",""));
//提醒學(xué)生數(shù)據(jù)發(fā)生改變
scoket.sendMessageAll(JSONObject.toJSONString(student));
pom.xml:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> </dependency>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于SpringBoot攔截器中Bean無(wú)法注入的問題
這兩天遇到SpringBoot攔截器中Bean無(wú)法注入問題。下面介紹關(guān)于SpringBoot攔截器中Bean無(wú)法注入的問題,感興趣的朋友一起看看吧2021-10-10
Java 獲取本機(jī)的IP與MAC地址實(shí)現(xiàn)詳解
這篇文章主要介紹了Java 獲取本機(jī)的IP與MAC地址實(shí)現(xiàn)詳解的相關(guān)資料,需要的朋友可以參考下2016-09-09
ProtoStuff不支持BigDecimal序列化及反序列化詳解
這篇文章主要為大家介紹了ProtoStuff不支持BigDecimal序列化/反序列化,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
SpringSecurity動(dòng)態(tài)加載用戶角色權(quán)限實(shí)現(xiàn)登錄及鑒權(quán)功能
這篇文章主要介紹了SpringSecurity動(dòng)態(tài)加載用戶角色權(quán)限實(shí)現(xiàn)登錄及鑒權(quán)功能,很多朋友感覺這個(gè)功能很難,今天小編通過實(shí)例代碼給大家講解,需要的朋友可以參考下2019-11-11
SpringCloud gateway如何修改返回?cái)?shù)據(jù)
這篇文章主要介紹了SpringCloud gateway如何修改返回?cái)?shù)據(jù)的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06
Java對(duì)稱與非對(duì)稱加密算法原理詳細(xì)講解
對(duì)稱加密算法指加密和解密使用相同密鑰的加密算法。對(duì)稱加密算法用來(lái)對(duì)敏感數(shù)據(jù)等信息進(jìn)行加密,非對(duì)稱加密算法指加密和解密使用不同密鑰的加密算法,也稱為公私鑰加密2022-11-11

