WebSocket实现数据库更新时前端页面刷新

本文详细介绍了使用Spring框架配置WebSocket并实现前后端实时通信的方法。包括WebSocketConfig配置类的定义,WebSocketServlet处理类的实现,以及前端JS代码的编写。通过实例展示了如何发送和接收消息,管理在线用户,并在关闭连接时进行相应的处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

后台代码:

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>

 

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值