Bootstrap

js-数据请求轮询与长轮询(客户端定时向服务器发送请求获取数据)

1.轮询

        客户端定时向服务器发送请求获取数据,服务存在数据就返回给客户端,如果无新的数据也返回一个应答,表面没有新的数据。

2.轮询实现

        js的setInterval函数设定5秒间隔发送请求。

const axios = require('axios');

function poll() {
    axios.get('http://example.com/data')
        .then(response => {
            // 处理响应数据
            console.log(response.data);

            // 无论是否有新数据,都继续轮询
            setTimeout(poll, 5000); // 每5秒轮询一次
        })
        .catch(error => {
            console.error(error);

            // 发生错误后继续轮询
            setTimeout(poll, 5000);
        });
}

// 开始轮询
poll();

3. 长轮询

        在轮询基础上进行的优化,客户端向服务器发送请求,如果服务器无数据更新则保持请求,待到请求超时或者响应接受到新的数据时再立即发送请求,发送错误后等待5秒再发送请求。

const axios = require('axios');

function longPoll() {
    axios.get('http://example.com/data')
        .then(response => {
            // 处理响应数据
            console.log(response.data);

            // 收到数据后立即再发送请求
            longPoll();
        })
        .catch(error => {
            console.error(error);

            // 发生错误后,等待5秒再发送请求
            setTimeout(longPoll, 5000);
        });
}

// 开始长轮询
longPoll();

实时获取数据WebScoket通信更加适用。

node.js-node.js作为服务器,前端使用WebSocket(单个TCP连接上进行全双工通讯的协议)-CSDN博客文章浏览阅读666次,点赞17次,收藏11次。node.js作为服务器,前端使用WebSocket(单个TCP连接上进行全双工通讯的协议) https://blog.csdn.net/2301_76671906/article/details/146199752?fromshare=blogdetail&sharetype=blogdetail&sharerId=146199752&sharerefer=PC&sharesource=2301_76671906&sharefrom=from_link

;