简单介绍websocket

WebSocket 是 HTML5 开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。

  • 事件:
    open Socket.onopen 连接建立时触发
    message Socket.onmessage 客户端接收服务端数据时触发
    error Socket.onerror 通信发生错误时触发
    close Socket.onclose 连接关闭时触发
  • 方法:
    Socket.send() 使用连接发送数据
    Socket.close() 关闭连接
  • 属性:
    readyState 只读属性 : 表示连接状态
    bufferedAmount 只读属性: 已被 send() 放入正在队列中等待传输,但是还没有发出的 UTF-8 文本字节数。

根据readyState属性可以判断webSocket的连接状态,该属性的值可以是下面几种:

0 :对应常量CONNECTING (numeric value 0),
正在建立连接连接,还没有完成。The connection has not yet been established.
1 :对应常量OPEN (numeric value 1),
连接成功建立,可以进行通信。The WebSocket connection is established and communication is possible.
2 :对应常量CLOSING (numeric value 2)
连接正在进行关闭握手,即将关闭。The connection is going through the closing handshake.
3 : 对应常量CLOSED (numeric value 3)
连接已经关闭或者根本没有建立。The connection has been closed or could not be opened.

或者:

switch (ws.readyState) {
  case WebSocket.CONNECTING:
    // do something
    break;
  case WebSocket.OPEN:
    // do something
    break;
  case WebSocket.CLOSING:
    // do something
    break;
  case WebSocket.CLOSED:
    // do something
    break;
  default:
    // this never happens
    break;
}

阮一峰博客参考 : http://www.ruanyifeng.com/blog/2017/05/websocket.html

使用demo:

// html代码片段:
<el-button @click="initWebSocket">点击连接websocket</el-button>


// js代码
//created(){
//	this.initWebSocket();
//},
methods:{
initWebSocket(){//初始化weosocket
        const wsuri = `ws:${imgURL}/web-socket/get-message-count`;
        this.websock = new WebSocket(wsuri);
        // 判断是否websocket是否已经打开,如果已经打开则直接发送数据  readyState
        if( this.websock.readyState !== WebSocket.OPEN ){
          this.websock.onopen = this.websocketonopen;
        }else{
          this.websocketsend(userid);
        }
        // this.websock.onopen = this.websocketonopen;
        this.websock.onerror = this.websocketonerror;
        this.websock.onmessage = this.websocketonmessage;
        this.websock.onclose = this.websocketclose;
      },
      //  连接建立之后执行send方法发送数据
      websocketonopen(){ 
        this.websocketsend();
      },
      websocket(){//连接建立失败重连
        this.initWebSocket();
      },
        //  数据接收
      websocketonmessage(e){    
        const redata = JSON.parse(e.data);
        this.infoNum = redata.count
        console.log(`数据接收`+ JSON.parse(e.data).count)
      },
      //  数据发送
      websocketsend(Data){      
        this.websock.send(Data);
        console.log(`数据发送`+Data)
      },
       //  关闭
      websocketclose(e){ 
        console.log('断开连接',e);
      }
}
Logo

前往低代码交流专区

更多推荐