WebSocket实现数据库更新时前端页面刷新
本文实例为大家分享了WebSocket实现数据库更新时前端页面刷新,供大家参考,具体内容如下
后台代码:
WebSocketConfig:
packagecom.x.common.websocket;
importorg.springframework.context.annotation.Bean;
importorg.springframework.context.annotation.Configuration;
importorg.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
publicclassWebSocketConfig{
@Bean
publicServerEndpointExporterserverEndpointExporter(){
returnnewServerEndpointExporter();
}
}
WebSocketServlet:
packagecom.x.common.websocket;
importcom.alibaba.fastjson.JSONObject;
importorg.springframework.stereotype.Component;
importjava.io.IOException;
importjava.util.Map;
importjava.util.concurrent.ConcurrentHashMap;
importjavax.websocket.*;
importjavax.websocket.server.PathParam;
importjavax.websocket.server.ServerEndpoint;
@ServerEndpoint("/websocket/{userId}")
@Component
publicclassWebSocketServlet{
privatestaticintonlineCount=0;
privatestaticMapclients=newConcurrentHashMap<>();
privateSessionsession;
privateStringuserId;
@OnOpen
publicvoidonOpen(@PathParam("userId")StringuserId,Sessionsession)throwsIOException{
this.userId=userId;
this.session=session;
addOnlineCount();
clients.put(userId,this);
System.out.println("已连接");
}
@OnClose
publicvoidonClose()throwsIOException{
clients.remove(userId);
subOnlineCount();
}
@OnMessage
publicvoidonMessage(Stringmessage)throwsIOException{
JSONObjectjsonTo=JSONObject.parseObject(message);
if(!jsonTo.get("To").equals("All")){
sendMessageTo("给一个人",jsonTo.get("To").toString());
}else{
sendMessageAll("给所有人");
}
}
@OnError
publicvoidonError(Sessionsession,Throwableerror){
error.printStackTrace();
}
publicvoidsendMessageTo(Stringmessage,StringTo)throwsIOException{
//session.getBasicRemote().sendText(message);
//session.getAsyncRemote().sendText(message);
for(WebSocketServletitem:clients.values()){
if(item.userId.equals(To)){
item.session.getAsyncRemote().sendText(message);
}
}
}
publicvoidsendMessageAll(Stringmessage)throwsIOException{
for(WebSocketServletitem:clients.values()){
item.session.getAsyncRemote().sendText(message);
}
}
publicstaticsynchronizedintgetOnlineCount(){
returnonlineCount;
}
publicstaticsynchronizedvoidaddOnlineCount(){
WebSocketServlet.onlineCount++;
}
publicstaticsynchronizedvoidsubOnlineCount(){
WebSocketServlet.onlineCount--;
}
publicstaticsynchronizedMapgetClients(){
returnclients;
}
}
JS代码:
varwebsocket=null;
//判断当前浏览器是否支持WebSocket
if('WebSocket'inwindow){
websocket=newWebSocket("ws://localhost:8086/websocket/1");
}else{
alert('当前浏览器Notsupportwebsocket')
}
//连接发生错误的回调方法
websocket.onerror=function(){
console.log("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen=function(){
console.log("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage=function(event){
//返回数据转JSON
varjson=JSON.parse(event.data);
//result为bootstraptable返回数据
varrows=result.rows;
for(vari=0;i
返回前台是调用方法:
@Autowired
privateWebSocketServletscoket;
//学生信息
XStudentInfoEntitystudent=xStudentInfoService.getObjectById(id.replace("\"",""));
//提醒学生数据发生改变
scoket.sendMessageAll(JSONObject.toJSONString(student));
pom.xml:
org.springframework
spring-websocket
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。