Skip to content

websocket工具函数(摘抄)

同事zq对原生websocket进行了二次封装,个人觉得方便实用,特记录。

工具代码:

js
const WS = function(obj) {
  /*
	websocket接口地址
	1、http请求还是https请求 前缀不一样
	2、ip地址host
	3、端口号
	*/
  const config = obj ? obj : {};
  const protocol = window.location.protocol == 'http:' ? 'ws://' : 'wss://';
  const host = 'localhost';
  const port = ':5477';
  const path = '/test';
  //接口地址url
  this.url = config.ip || protocol + host + port + path;
  //socket对象
  this.socket;
  //心跳状态  为false时不能执行操作 等待重连
  this.isHeartflag = false;
  //重连状态  避免不间断的重连操作
  this.isReconnect = false;

  //服务器连接成功
  this.onopen = () => {
    this.isHeartflag = true;
  };
  //服务器向前端推送消息时触发
  this.onmessage = () => {
    //处理各种推送消息
  };
  //Ws连接关闭后触发
  this.onclose = () => {
    this.reConnect();
    console.log('Websocket Close');
  };
  //Ws报错后触发
  this.onerror = () => {
    console.log('Websocket Error');
    this.isHeartflag = false;
    this.reConnect();
  };
  this.send = e => {
    this.socket.send(e);
  };
  //初始化websocket连接
  this.initWs();
};
//初始化websocket连接
WS.prototype.initWs = function() {
  window.WebSocket = window.WebSocket || window.MozWebSocket;
  // 检测浏览器支持
  if (!window.WebSocket) {
    console.error('错误: 浏览器不支持websocket');
    return;
  }
  var that = this;
  this.socket = new WebSocket(this.url); // 创建连接并注册响应函数
  this.socket.onopen = function(e) {
    that.onopen(e);
  };
  this.socket.onmessage = function(e) {
    that.onmessage(e);
  };
  this.socket.onclose = function(e) {
    that.onclose(e);
    that.socket = null; // 清理
  };
  this.socket.onerror = function(e) {
    that.onerror(e);
  };
  return this;
};
// 重连
WS.prototype.reConnect = function() {
  if (this.isReconnect) return;
  this.isReconnect = true;
  //没连接上会一直重连,设置延迟避免请求过多
  setTimeout(() => {
    this.initWs();
    this.isReconnect = false;
  }, 2000);
};

export default WS;

使用方法:

function中传入websocket地址返回ws,ws内部方法可以覆盖使用。使用该函数默认websocket断开时自动重连,如果不想可以覆盖onclose的监听。

鄂ICP备19018246号-1