WebSocket Refresh Front Page When Updating Database
- 2021-07-16 02:28:23
- OfStack
This article example for everyone to share WebSocket database update when the front-end page refresh, for your reference, the specific content is as follows
Background code:
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(" Connected ");
}
@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(" To 1 Individual ", jsonTo.get("To").toString());
}else{
sendMessageAll(" To everyone ");
}
}
@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 code:
var websocket = null;
// Determine whether the current browser supports WebSocket
if ('WebSocket' in window) {
websocket = new WebSocket("ws://localhost:8086/websocket/1");
} else {
alert(' Current browser Not support websocket')
}
// Callback method with connection error
websocket.onerror = function() {
console.log("WebSocket Connection error occurred ");
};
// Callback method for successful connection establishment
websocket.onopen = function() {
console.log("WebSocket Connection succeeded ");
}
// Callback method for receiving message
websocket.onmessage = function(event) {
// Return data to JSON
var json=JSON.parse(event.data);
//result For bootstrap table Return data
var rows=result.rows;
for(var i=0;i<rows.length;i++){
var row=rows[i];
if(row.id==json.id){
// Judgment column Id Refresh the table at the same time
//$('#dataGrid').bootstrapTable('updateByUniqueId', {index: i, row: row});'refresh'
$('#dataGrid').bootstrapTable('refresh');
}
}
console.log(event.data);
}
// Callback method for connection closure
websocket.onclose = function() {
console.log("WebSocket Connection closed ");
}
// Listen for window closing events, and when the window is closed, take the initiative to close it websocket Connection to prevent the window from being closed before the connection is disconnected. server End will throw an exception.
window.onbeforeunload = function() {
closeWebSocket();
}
// Shut down WebSocket Connect
function closeWebSocket() {
websocket.close();
}
Returning to the foreground is to call the method:
@Autowired
private WebSocketServlet scoket;
// Student information
XStudentInfoEntity student = xStudentInfoService.getObjectById(id.replace("\"",""));
// Remind students that the data has changed
scoket.sendMessageAll(JSONObject.toJSONString(student));
pom. xml:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
</dependency>