前端基于WebSocket封装

本文介绍了前端如何处理WebSocket连接,包括在无心跳的情况下,如何处理短连接并实现重新连接的逻辑。文中详细讲解了连接建立、关闭、信息接收以及消息发送的方法。

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

1.无心跳,短开连接之后重新连。
class webSocketClass {
  constructor(name) {
    this.lockReconnect = false;
    this.localUrl = "ws://XXXXXX";
    this.wsUrl = "";
    this.globalCallback = null;
    this.userClose = false;
    this.createWebSocket(name);
  }

  createWebSocket(url) {
    let that = this;
    that.wsUrl = url;
    try {
      that.ws = new WebSocket(that.localUrl + that.wsUrl);
      that.initEventHandle();
    } catch (e) {
      that.reconnect(url);
    }
  }

  //初始化
  initEventHandle() {
    let that = this;
    //连接成功建立后响应
    that.ws.onopen = function() {
      console.log("连接成功");
    }; 
    //连接关闭后响应
    that.ws.onclose = function() {
      if (!that.userClose) {
        that.reconnect(that.wsUrl); //重连
      }
    };
    that.ws.onerror = function() {
      if (!that.userClose) {
        that.reconnect(that.wsUrl); //重连
      }
    };
    that.ws.onmessage = function() {
      that.getWebSocketMsg(that.globalCallback);
    };
  }

  reconnect(url) {
    let that = this;
    if (that.lockReconnect) return;
    that.lockReconnect = true; //没连接上会一直重连,设置延迟避免请求过多
    setTimeout(function() {
      that.createWebSocket(url);
      that.lockReconnect = false;
    }, 30000);
  }

  webSocketSendMsg(msg) {
    this.ws.send(msg);
  }

  getWebSocketMsg(callback) {
    this.ws.onmessage = ev => {
      callback && callback(ev);
    };
  }

  closeSocket() {
    let that = this;
    if (that.ws) {
      that.userClose = true;
      that.ws.close();
    }
  }
}
export default webSocketClass;

调用方法

import WebSocketClass from '@/services/webSocket';
let ws = new WebSocketClass(url);

关闭方法

ws.closeSocket();

获取socket返回的信息

ws.getWebSocketMsg(ev => {
  console.log(JSON.parse(ev.data));
});

向socket发送消息

ws.webSocketSendMsg(msg);
### 如何封装 WebSocket 代码 WebSocket 是一种允许在单个 TCP 连接上进行全双工通信的协议。为了提高可维护性和重用性,通常会将 WebSocket 的功能封装成一个模块或类。以下是基于 JavaScript 和 PHP 的两种常见封装方式。 #### 基于 Vue.js 或前端框架的封装示例 以下是一个使用 Vue3 `setup` 方法中的 WebSocket 封装示例: ```javascript // utils/WebSocketUtil.js export default class WebSocketUtil { constructor(url) { this.url = url; this.ws = null; } connect() { if (!this.ws || this.ws.readyState === WebSocket.CLOSED) { this.ws = new WebSocket(this.url); this.initEventHandlers(); } } initEventHandlers() { this.ws.onopen = () => console.log('WebSocket connection opened'); this.ws.onerror = (error) => console.error('WebSocket error:', error); this.ws.onclose = () => console.log('WebSocket connection closed'); } send(data) { if (this.ws && this.ws.readyState === WebSocket.OPEN) { this.ws.send(JSON.stringify(data)); } else { console.warn('WebSocket is not open or does not exist.'); } } onMessage(callback) { if (this.ws) { this.ws.onmessage = callback; } } close() { if (this.ws) { this.ws.close(); } } } ``` 上述代码定义了一个通用的 WebSocket 工具类[^2],可以轻松集成到任何项目中。它支持连接管理、消息监听以及关闭操作等功能。 --- #### 基于 PHP 的 WebSocket 封装示例 PHP 中可以通过 Swoole 扩展或其他库实现 WebSocket 功能。下面展示了一种基本的封装方法: ```php <?php class WebSocketServer { private $server; public function __construct($host, $port) { $this->server = new swoole_websocket_server($host, $port); $this->server->on('open', [$this, 'onOpen']); $this->server->on('message', [$this, 'onMessage']); $this->server->on('close', [$this, 'onClose']); echo "WebSocket server started at ws://$host:$port\n"; } public function start() { $this->server->start(); } public function onOpen($server, $request) { echo "Client connected: {$request->fd}\n"; } public function onMessage($server, $frame) { $data = json_decode($frame->data, true); foreach ($server->connections as $connection) { $server->push($connection, json_encode([ 'type' => 'broadcast', 'content' => $data['message'] ])); } } public function onClose($server, $fd) { echo "Client disconnected: $fd\n"; } } $ws = new WebSocketServer('0.0.0.0', 9502); $ws->start(); ?> ``` 这段代码展示了如何利用 Swoole 创建并启动一个 WebSocket 服务端[^4]。通过事件驱动的方式处理客户端连接、消息广播和断开逻辑。 --- #### UniApp 下的 WebSocket 封装 对于跨平台开发工具 UniApp,也可以对其内置的 WebSocket API 进行简单封装: ```javascript const WebSocketWrapper = { socketTask: null, init(url) { if (!this.socketTask || this.socketTask.readyState !== 1) { this.socketTask = uni.connectSocket({ url, success(res) { console.log('Connected to WebSocket:', res); }, fail(err) { console.error('Failed to connect WebSocket:', err); } }); this.bindEvents(); } }, bindEvents() { this.socketTask.onMessage((res) => { console.log('Received message:', res.data); }); this.socketTask.onClose(() => { console.log('WebSocket connection closed.'); }); }, sendMessage(message) { if (this.socketTask && this.socketTask.readyState === 1) { this.socketTask.send({ data: JSON.stringify(message) }); } else { console.warn('WebSocket is not ready.'); } }, close() { if (this.socketTask) { this.socketTask.close(); } } }; export default WebSocketWrapper; ``` 该封装适用于 UniApp 平台上的应用开发需求[^3],能够简化 WebSocket 的初始化、消息收发及资源释放过程。 --- ### 总结 无论是前端还是后端,合理地封装 WebSocket 可以为项目的扩展提供便利。以上三种方案分别针对不同的技术栈进行了优化设计,可以根据实际业务场景选择合适的实现方式。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值