zl程序教程

您现在的位置是:首页 >  Javascript

当前栏目

在Vue项目中使用WebSocket技术

2023-03-15 21:59:14 时间

WebSocket 协议自2008年诞生2011年成为国际标准以来。目前所有浏览器都已经支持了。因此我们不需要担心在项目中使用是否会有其他问题,WebSocket实现了浏览器与服务器全双工通信,服务器可以主动向客户端推送信息,客户端也可以主动向服务器发送信息。

MDN上面有详细的文档,这里就不过多介绍,我们直接在vue项目上使用WebSocket,其实可以借助库实现,但是这个项目我们使用原生的,毕竟代码不多,也没必要在安装个依赖。

WebSocket属性很多,用到了onopen、onerror、onmessage和onclose,在methods方法中定义几个函数。

// socket连接成功
open() {
  console.log("socket连接成功");
},
// socket连接失败
error() {
  console.log("连接错误");
},
// 接收消息
getMessage(msg) {
  console.log("==websocket接收数据==");
  console.log(msg.data);
},
// 发送数据
send() {
  this.socket.send("这是传送数据");
},
// 关闭socket
close() {
  console.log("socket已经关闭");
}

接下来初始化方法,实例化socket

init() {
  if (typeof WebSocket === "undefined") {
    alert("您的浏览器不支持socket");
  } else {
    // 实例化socket
    this.socket = new WebSocket(this.path);
    // 监听socket连接
    this.socket.onopen = this.open;
    // 监听socket错误信息
    this.socket.onerror = this.error;
    // 监听socket消息
    this.socket.onmessage = this.getMessage;
  }
},

方法都定义完成了,剩下就是初始化socket和关闭socket了。

data() {
  return {
    path: "",
    socket: ""
  };
},
mounted() {
  // 初始化
  this.init();
},
destroyed() {
  // 销毁监听
  this.socket.onclose = this.close;
}

到这就是所有的代码,在浏览器中打开,测试下

能接收到数据,也能发送数据。