溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

使用WebSocket怎么實現(xiàn)數(shù)據(jù)庫更新時前端頁面刷新

發(fā)布時間:2021-05-27 17:51:32 來源:億速云 閱讀:673 作者:Leah 欄目:編程語言

這期內容當中小編將會給大家?guī)碛嘘P使用WebSocket怎么實現(xiàn)數(shù)據(jù)庫更新時前端頁面刷新,文章內容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

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("給一個人", 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;
 
//判斷當前瀏覽器是否支持WebSocket
if ('WebSocket' in window) {
 websocket = new WebSocket("ws://localhost:8086/websocket/1");
} else {
 alert('當前瀏覽器 Not support websocket')
}
 
//連接發(fā)生錯誤的回調方法
websocket.onerror = function() {
 console.log("WebSocket連接發(fā)生錯誤");
};
 
//連接成功建立的回調方法
websocket.onopen = function() {
 console.log("WebSocket連接成功");
}
 
//接收到消息的回調方法
websocket.onmessage = function(event) {
 //返回數(shù)據(jù)轉JSON
 var json=JSON.parse(event.data);
 //result為bootstrap table 返回數(shù)據(jù)
 var rows=result.rows;
 for(var i=0;i<rows.length;i++){
 var row=rows[i];
 if(row.id==json.id){
 //判斷列Id相同時刷新表格
 //$('#dataGrid').bootstrapTable('updateByUniqueId', {index: i, row: row});'refresh'
 $('#dataGrid').bootstrapTable('refresh');
 }
 }
 console.log(event.data);
}
 
//連接關閉的回調方法
websocket.onclose = function() {
 console.log("WebSocket連接關閉");
}
 
//監(jiān)聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。
window.onbeforeunload = function() {
 closeWebSocket();
}
 
//關閉WebSocket連接
function closeWebSocket() {
 websocket.close();
}

返回前臺是調用方法:

@Autowired
private WebSocketServlet scoket;
 
//學生信息
XStudentInfoEntity student = xStudentInfoService.getObjectById(id.replace("\"",""));
//提醒學生數(shù)據(jù)發(fā)生改變
scoket.sendMessageAll(JSONObject.toJSONString(student));

pom.xml: 

<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-websocket</artifactId>
</dependency>

上述就是小編為大家分享的使用WebSocket怎么實現(xiàn)數(shù)據(jù)庫更新時前端頁面刷新了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI