webSocket前端+webSocket封装

一、websocket基础

/**
 * 初始化websocket连接
 */
function initWebSocket() {
	let uId = 1;
	var websocket = null;
	if('WebSocket' in window) {
		websocket = new WebSocket("ws://localhost:8009/webSocket"+uId );//请求的地址
	} else {
		alert("该浏览器不支持websocket!");
	}
	websocket.onopen = function(event) {
		console.log("建立连接");
		websocket.send('Hello WebSockets!');//给后端发消息
	}
	websocket.onclose = function(event) {
		console.log('连接关闭')
		reconnect(); //尝试重连websocket
	}
	//建立通信后,监听到后端的数据传递
	websocket.onmessage = function(event) {
		let data = JSON.parse(event.data);
		//业务处理....
		if(data.step == 1){
		   alert(data.msg);
		}
	}
	websocket.onerror = function() {
		// notify.warn("websocket通信发生错误!");
		// initWebSocket()
	}
	window.onbeforeunload = function() {
		websocket.close();
	}
// 重连
function reconnect() {
	console.log("正在重连");
	// 进行重连
	setTimeout(function () {
		initWebSocket();
	}, 1000);
}

二、webSocket定义通用类
1.创建js文件用于封装webSocket

class MyWebScoket {
  constructor(socketUrl) {
    // super(socketUrl);
    this.onopen = null
    this.onclose = null
    this.onmessage = null
    this.onerror = null
    this.socketUrl = socketUrl
    this.init()
  }

  init() {
    this.socket = new WebSocket(this.socketUrl);
    this.socket.onopen = function (event) {
      console.log(event, '建立连接')
      if (this.onopen) {
        this.onopen(event)
      }
    }
    this.socket.onmessage = function (event) {
      console.log(event, '连接关闭')
      if (this.onmessage) {
        this.onmessage(event)
      }
    }
    this.socket.onerror = function (event) {
      console.log(event, 'websocket通信发生错误')
      if (this.onerror) {
        this.onerror(event)
      }
    }
    this.socket.onclose = function (event) {
      console.log(event, '处理业务')
      if (this.onclose) {
        this.onclose(event)
      }
    }
  }
}

export default MyWebScoket

2.使用(vue)

  import websocket from "./websocket.js"

  setWebsocket(){
      this.socket = new MyWebScoket(socketUrl)//socketUrl请求的地址
      this.socket.onopen = this.onopen.bind(this)
      this.socket.onclose = this.onclose .bind(this)
      this.socket.onmessage = this.onmessage .bind(this)
      this.socket.onerror = this.onerror.bind(this)
    },
    onopen(event){
      //业务处理
    },
    onclose(event){
      //业务处理
    },
    onmessage(event){
      //业务处理
    },
    onerror(event){
      //业务处理
    },

你可能感兴趣的:(前端,vue.js,javascript)