您好,登錄后才能下訂單哦!
這期內容當中小編將會給大家帶來有關使用WebSocket怎么實現數據庫更新時前端頁面刷新,文章內容豐富且以專業的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。
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') } //連接發生錯誤的回調方法 websocket.onerror = function() { console.log("WebSocket連接發生錯誤"); }; //連接成功建立的回調方法 websocket.onopen = function() { console.log("WebSocket連接成功"); } //接收到消息的回調方法 websocket.onmessage = function(event) { //返回數據轉JSON var json=JSON.parse(event.data); //result為bootstrap table 返回數據 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連接關閉"); } //監聽窗口關閉事件,當窗口關閉時,主動去關閉websocket連接,防止連接還沒斷開就關閉窗口,server端會拋異常。 window.onbeforeunload = function() { closeWebSocket(); } //關閉WebSocket連接 function closeWebSocket() { websocket.close(); }
返回前臺是調用方法:
@Autowired private WebSocketServlet scoket; //學生信息 XStudentInfoEntity student = xStudentInfoService.getObjectById(id.replace("\"","")); //提醒學生數據發生改變 scoket.sendMessageAll(JSONObject.toJSONString(student));
pom.xml:
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-websocket</artifactId> </dependency>
上述就是小編為大家分享的使用WebSocket怎么實現數據庫更新時前端頁面刷新了,如果剛好有類似的疑惑,不妨參照上述分析進行理解。如果想知道更多相關知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。