webSocket前端+webSocket封装

一、websocket基础
二、websocket 封装
三、websocket 测试接通

一、websocket 基础

// WebSocket构造函数,创建WebSocket对象
let ws = new WebSocket('ws://localhost:8888')
// 连接成功后的回调函数
ws.onopen = function (params) {
  console.log('客户端连接成功')
  // 向服务器发送消息
  ws.send('hello')
};
// 从服务器接受到信息时的回调函数
ws.onmessage = function (e) {
  console.log('收到服务器响应', e.data)
};
// 连接关闭后的回调函数
ws.onclose = function(evt) {
  console.log("关闭客户端连接");
};

// 连接失败后的回调函数
ws.onerror = function (evt) {
  console.log("连接失败了");
};


// 监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,这样服务端会抛异常。
window.onbeforeunload = function() {
    ws.close();
}

二、websocket 封装

class MyWebScoket {
  constructor(socketUrl) {
    // super(socketUrl);
    this.onopenFn = null
    this.oncloseFn = null
    this.onmessageFn = null
    this.onerrorFn = null
    this.socketUrl = socketUrl
    this.socket = null
    this.init()
  }

  init() {
    let self = this
    let timeStep = new Date().getTime();
    self.socket = new WebSocket(self.socketUrl + timeStep);
    self.socket.onopen = function (event) {
      if (self.onopenFn) {
        self.onopenFn(event)
      }
    }
    self.socket.onmessageFn = function (event) {
      console.log(event, '连接关闭')
      if (self.onmessageFn) {
        self.onmessageFn(event)
      }
    }
    self.socket.onerrorFn = function (event) {
      console.log(event, 'websocket通信发生错误')
      if (self.onerrorFn) {
        self.onerrorFn(event)
      }
    }
    self.socket.oncloseFn = function (event) {
      console.log(event, '处理业务')
      if (self.oncloseFn) {
        self.oncloseFn(event)
      }
    }
  }
  close() {
    this.socket.close()
  }
}

export default MyWebScoket

2.使用(vue)

  import websocket from "./websocket.js"

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

三、websocket 测试接通

下载包:https://download.csdn.net/download/Web_Notes/88695650?spm=1001.2014.3001.5501

项目介绍:可以用来测试websocket接通后的效果,方便前端调整,就不用等后端接口了。
index.js为主要文件,运行命令为 node index.js

使用方法:
1.index.js 页面
在这里插入图片描述
2.index.html
在这里插入图片描述

3.浏览器打开index.html,打开控制台,如果能收到index.js发送的内容,就没问题了。
就把index.html里面websocket 请求的地址 复制到你其他需要使用的项目里,就可以接收websocket 进行调整处理了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值