在springboot项目前端遇到websocket无法更新最新数据渲染问题

在springboot项目前端遇到websocket无法更新最新数据渲染问题

<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Example</title>
</head>
<body>

<!-- 表格一 -->
<table class="table table-bordered">
    <thead>
    <tr>
        <th>公司名称</th>
        <th>当前价格</th>
    </tr>
    </thead>
    <tbody id="company-table-body">
    </tbody>
</table>

<!-- 表格二 -->
<table class="table table-bordered">
    <thead>
    <tr>
        <th>ID</th>
        <th>买入金额</th>
        <th>买入数量</th>
    </tr>
    </thead>
    <tbody id="buy-orders-table-body">
    </tbody>
</table>

<!-- 表格三 -->
<table class="table table-bordered">
    <thead>
    <tr>
        <th>ID</th>
        <th>卖出金额</th>
        <th>卖出数量</th>
    </tr>
    </thead>
    <tbody id="sell-orders-table-body">
    </tbody>
</table>

<script>
    // 保存当前数据的变量
    let shareCapitalList = [];
    let buyOrdersList = [];
    let sellOrdersList = [];

    const ws = new WebSocket("ws://localhost:8081/websocket");

    ws.onopen = function() {
        console.log('WebSocket connected');
    }

    ws.onmessage = function(event) {
        console.log(event.data);
        if (event.data.startsWith("shareCapitalList:")) {
            shareCapitalList = JSON.parse(event.data.substring(17));
            renderCompanyTable(shareCapitalList);
        } else if (event.data.startsWith("buyOrdersList:")) {
            buyOrdersList = JSON.parse(event.data.substring(14));
            renderBuyOrdersTable(buyOrdersList);
        } else if (event.data.startsWith("sellOrdersList:")) {
            sellOrdersList = JSON.parse(event.data.substring(15));
            renderSellOrdersTable(sellOrdersList);
        }
    }


    ws.onclose = function() {
        console.log('WebSocket disconnected');
    }

    function renderTableData(data, tbodyId) {
        // 获取 tbody 元素
        const tbody = document.getElementById(tbodyId);

        // 清空之前的数据
        tbody.innerHTML = "";

        // 生成 HTML 代码
        const html = data.map((item) => {
            let rowHtml = "";
            for (const [key, value] of Object.entries(item)) {
                rowHtml += `<td>${value}</td>`;
            }
            return `<tr>${rowHtml}</tr>`;
        }).join("");

        // 更新表格数据
        tbody.innerHTML = html;
    }

    function renderCompanyTable(data) {
        // 渲染表格一数据
        renderTableData(data, "company-table-body");
    }

    function renderBuyOrdersTable(data) {
        // 渲染表格二数据
        renderTableData(data, "buy-orders-table-body");
    }

    function renderSellOrdersTable(data) {
        // 渲染表格三数据
        renderTableData(data, "sell-orders-table-body");
    }

</script>
</body>
</html>

初始化数据可以正常渲染如下图

img

但是websocket发布了新的数据时,前端无法正常渲染新的数据,还是最初的数据如下图

img

我想要前端可以正常自动渲染最新的数据

这几个判断通过了吗

img

【相关推荐】



  • 这个问题的回答你可以参考下: https://ask.csdn.net/questions/335749
  • 这篇博客你也可以参考下:springboot整合海康视频到websocket接口前端显示
  • 您还可以看一下 张颜源老师的新版本录制websocket教程整合SpringBoot socketjs视频教程课程中的 14、websocket结合spring相关拦截器使用,及握手拦截器介绍小节, 巩固相关知识点
  • 除此之外, 这篇博客: 基于springboot实现websocket的客户端、服务端中的 3、websocket服务端类 部分也许能够解决你的问题, 你可以仔细阅读以下内容或跳转源博客中阅读:
    package com.gjx.server.webserver.server;
    
    import org.springframework.web.bind.annotation.RestController;
    import javax.websocket.*;
    import javax.websocket.server.ServerEndpoint;
    import java.io.IOException;
    import java.util.Map;
    import java.util.concurrent.ConcurrentHashMap;
    
    /**
     * @Author gjx
     * @email 13450753745@163.com
     * @description websocket的服务端类
     * @Date 2019/10/14
     */
    @ServerEndpoint("/serverTest")
    @RestController
    public class WebSocketServer {
    
        /**
         *存放所有的在线客户端
         * */
        private static Map<String, Session> clients = new ConcurrentHashMap<>();
    
        /**
         * 客户端与服务端连接时触发执行事件
         */
        @OnOpen
        public void onOpen(Session session) throws InterruptedException, IOException {
            System.out.println("有新的客户端连接进来了");
            clients.put(session.getId(), session);
        }
    
        /**
         * 向客户端发送字符串信息
         */
        private static void sendMsg(Session session, String msg) throws IOException {
            session.getBasicRemote().sendText(msg);
        }
    
        /**
         *接收到消息后的处理方式,其中包含客户端的普通信息和心跳包信息,
         * 简单区别处理
         */
        @OnMessage
        public void onMessage(Session session, String msg) throws Exception {
    
            if (!msg.equals("keepalive")){
                System.out.println("服务端收到消息:" + msg);
                Thread.sleep(3000L);
                sendMsg(session,msg);
            }else{
                System.out.println("心跳维护包:" + msg);
            }
        }
    
        @OnClose
        public void onClose(Session session) {
            System.out.println("有客户端断开连接了,断开客户为:" + session.getId());
            clients.remove(session.getId());
        }
    
        @OnError
        public void onError(Throwable throwable) {
            System.out.println("服务端出现错误");
            throwable.printStackTrace();
        }
    
    }
    
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^