webSocker消息推送,ajax轮询

AJAX 实现消息推送

AJAX(Asynchronous JavaScript and XML)允许你在不重新加载整个页面的情况下,与服务器进行数据交换。但是,传统的AJAX并不直接支持实时消息推送,因为它基于请求-响应模式。为了模拟消息推送,你可以使用轮询(polling)或长轮询(long-polling)技术。

AJAX 实现消息推送

AJAX(Asynchronous JavaScript and XML)允许你在不重新加载整个页面的情况下,与服务器进行数据交换。但是,传统的AJAX并不直接支持实时消息推送,因为它基于请求-响应模式。为了模拟消息推送,你可以使用轮询(polling)或长轮询(long-polling)技术。

轮询

轮询是定期向服务器发送请求,以检查是否有新的消息。这种方法简单但效率较低,因为即使在没有新消息的情况下,也会频繁地发送请求。

function pollForMessages() {
    $.ajax({
        url: '/messages', // 假设这是获取消息的API端点
        method: 'GET',
        success: function(data) {
            // 处理接收到的消息
            console.log(data);
            
            // 等待一段时间后再次轮询
            setTimeout(pollForMessages, 5000); // 每5秒轮询一次
        },
        error: function() {
            // 处理请求失败的情况
            setTimeout(pollForMessages, 10000); // 等待更长时间后重试
        }
    });
}

// 开始轮询
pollForMessages();

WebSocket 实现消息推送

WebSocket 提供了一个全双工的通信通道,允许服务器主动向客户端推送消息。一旦建立了WebSocket连接,服务器和客户端就可以随时向对方发送消息,而不需要像AJAX那样频繁地发起请求。

WebSocket 客户端实现

var socket = new WebSocket('ws://your-server-url');

socket.onopen = function(event) {
    // 连接打开后,你可以向服务器发送消息
    socket.send('Hello Server!');
};

socket.onmessage = function(event) {
    // 当收到服务器发来的消息时,触发此事件
    console.log('Received:', event.data);
};

socket.onerror = function(error) {
    // 处理错误
    console.error('WebSocket Error:', error);
};

socket.onclose = function(event) {
    // 连接关闭时触发
    console.log('WebSocket is closed now.');
};

WebSocket 服务器端实现

// WebSocketMessenger(快递服务公司)
class WebSocketManager {
  constructor(url = null, userId = null, receiveMessageCallback = null) {
    this.socket = null // WebSocket 对象
    this.sendTimeObj = null // 发送信息给服务端的重复调用的时间定时器
    this.reconnectTimeObj = null // 尝试链接的宏观定时器
    this.reconnectTimeDistance = 5000 // 重连间隔,单位:毫秒
    this.maxReconnectAttempts = 10 // 最大重连尝试次数
    this.reconnectAttempts = 0 // 当前重连尝试次数
    this.id = userId //用户ID(业务逻辑,根据自己业务需求调整)
    this.url = url // WebSocket 连接地址
    this.receiveMessageCallback = receiveMessageCallback // 接收消息回调函数
  }

  /**
   * 开启WebSocket
   */
  async start() {
    if (this.url && this.id) {
      // 连接WebSocket
      this.connectWebSocket()
    } else {
      console.error('WebSocket erros: 请传入连接地址和用户id')
    }
  }

  /**
   * 创建WebSocket连接, 超级快递车
   */
  connectWebSocket() {
    // 通过id生成唯一值(服务端要求,具体根据自己业务去调整)
    let id = `${this.id}-${Math.random()}`
    // 创建 WebSocket 对象
    this.socket = new WebSocket(this.url, id) // 快递员(WebSocket连接实例

    // 处理连接打开事件
    this.socket.onopen = (event) => {
      // 给服务端发送第一条反馈信息
      this.startSendServe()
    }

    // 处理接收到消息事件
    this.socket.onmessage = (event) => {
      this.receiveMessage(event)
    }

    // 处理连接关闭事件
    this.socket.onclose = (event) => {
      // 清除定时器
      clearTimeout(this.sendTimeObj)
      clearTimeout(this.reconnectTimeObj)
      // 尝试重连
      if (this.reconnectAttempts < this.maxReconnectAttempts) {
        this.reconnectAttempts++
        console.log('重试链接次数:'+ this.reconnectAttempts)
        this.reconnectTimeObj = setTimeout(() => {
          this.connectWebSocket()
        }, this.reconnectTimeDistance)
      } else {
        // 重置重连次数
        this.reconnectAttempts = 0
        console.error(
          'WebSocketManager erros: Max reconnect attempts reached. Unable to reconnect.'
        )
      }
    }

    // 处理 WebSocket 错误事件
    this.socket.onerror = (event) => {
      console.error('WebSocketManager error:', event)
    }
  }

  /**
   * 发送给node的第一条信息
   */
  startSendServe() {

    this.sendMessage('hi I come from client')
  }

  /**
   * 发送消息
   * @param {String} message 消息内容
   */
  sendMessage(message) {
    if (this.socket.readyState === WebSocket.OPEN) {
      this.socket.send(message)
    } else {
      console.error(
        'WebSocketManager error: WebSocket connection is not open. Unable to send message.'
      )
    }
  }

  /**
   * 接收到消息
   */
  receiveMessage(event) {
    // 根据业务自行处理
    console.log('receiveMessage:', event.data)
    this.receiveMessageCallback && this.receiveMessageCallback(event.data)
  }

  /**
   * 关闭连接
   */
  closeWebSocket() {
    this.socket.close()
    // 清除定时器 重置重连次数
    clearTimeout(this.sendTimeObj)
    clearTimeout(this.reconnectTimeObj)
    this.reconnectAttempts = 0
  }
}

使用Demo

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./webSocketManager.js"></script>
    <script>
        // const WebSocketManager = require('./webSocketManager.js')
        console.log(WebSocketManager)
        /**
         * 接收消息回调
         */
        const receiveMessage = (res)=>{
            console.log('接收消息回调:',res)
        }
        const socketManager = new WebSocketManager('ws://localhost:3000', 'userid292992', receiveMessage)
        socketManager.start()

    </script>
</head>

相关推荐

  1. webSocker消息ajax

    2024-07-21 14:02:03       20 阅读
  2. uniapp+极光做消息

    2024-07-21 14:02:03       48 阅读
  3. Springboot+WebSocket实现消息

    2024-07-21 14:02:03       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-21 14:02:03       52 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-21 14:02:03       54 阅读
  3. 在Django里面运行非项目文件

    2024-07-21 14:02:03       45 阅读
  4. Python语言-面向对象

    2024-07-21 14:02:03       55 阅读

热门阅读

  1. 基于边缘检测和HSV的图像识别算法

    2024-07-21 14:02:03       15 阅读
  2. 黄金分割率g 和圆周率pi 有什么数学关系?

    2024-07-21 14:02:03       16 阅读
  3. 统计所有可行路径(动态规划)

    2024-07-21 14:02:03       15 阅读
  4. Python之后端Django(五)

    2024-07-21 14:02:03       18 阅读
  5. Python基础学习攻略:从入门到进阶的完整路径

    2024-07-21 14:02:03       14 阅读
  6. 前端算法入门【栈】

    2024-07-21 14:02:03       16 阅读
  7. watch监听vue2与vue3的写法

    2024-07-21 14:02:03       21 阅读
  8. 类 WAS_CLIPSeg_Model_Loade

    2024-07-21 14:02:03       20 阅读
  9. powerbulder中的destroy 和 setnull

    2024-07-21 14:02:03       12 阅读