websocket双向通信

使用websocket建立客户端与服务器的双向连接

实现效果:

实现代码:

1.init方法:

init: function () {
  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连接
    this.socket.onclose = this.websocketclose
  }
},

path变量:

export var pathFile = "ws://192.168.1.145:8081/hawkeye/";

path: pathFile+"webSocket/",

2.建立连接:

open: function (e) {
  let data = this.network+"_"+this.partition+"_nodeId";
  this.send(data);
  console.log("socket连接成功")
},

3.给服务端发送消息:

send: function (Data) {
  this.socket.send(Data);
},

4.接收消息:

getMessage: function (msg) {
  var data = JSON.parse(msg.data);
}

5.断开连接:

websocketclose(e){  //关闭
  console.log('断开连接',e);
},

6.错误提醒方法:

error: function () {
  console.log("连接错误")
},

注意:

1.可以手动关闭websocket连接:this.socket.close();

2.若是需要在某种情况下要重新给服务端发送数据,可以直接let data = this.network+"_"+this.partition+"_nodeId";   this.send(data);因为一直处于连接中

3.若是在一进来页面就要开始websocket连接,可以直接在open建立连接时就发送数据。

4.双向通信时都是使用string字符串传输。

猜你喜欢

转载自www.cnblogs.com/5201314m/p/11997241.html