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>
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

前端成长营

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值