Detailed explanation and use of HTML5 WebSocket

Students who have never used WebSocket may sound difficult, but it is actually very simple. This chapter explains the basic information of WebSocket and provides code examples

What are WebSockets?

WebSocket is a protocol provided by HTML5 for full-duplex communication over a single TCP connection. (two-way communication protocol)

What does WebSocket do?

Realize two-way communication between the client and the server, allowing the server to actively push data to the client.

In  the WebSocket API  , the browser and the server only need to complete a handshake, and a persistent connection can be created directly between the two, and two-way data transmission can be performed.

What is the difference between WebSocket and HTTP?

Same point:

        1.  WebSocket  is the same reliable transmission protocol based on TCP ;

Different score:

        1.  WebSocket   can send or receive information in two directions, while HTTP is one-way ( HTTP communication can only be initiated by the client, and does not have the ability to actively push the server );

        2.  The use of WebSocket   requires a handshake between the client and the server first. After the two establish a connection, they can communicate normally in two directions. HTTP is an active  Request corresponding to a passive Response;

Protocol identifier for WebSocket?

If the server URL is HTTP , then  WebSocket   corresponds to ws

If the server URL is  HTTPS  encrypted, then WebSocket   corresponds to wss

Summary of the role of WebSocket?

WebSocket   is a protocol produced to meet the requirement of two-way communication with the server on the web application.

Compared with polling  HTTP  requests, WebSocket saves server resources and effectively improves efficiency.

Common methods of WebSocket

common method describe
Socket.send() Send information to the server through Socket
Socket.close() Close the Socket connection

Common properties of WebSocket

common attributes describe
Socket.readyState Get the current link status 0: Connecting, 1: The connection is normal and can communicate, 2: The connection is closing, 3: The connection is closed/connection failed
Socket.url Get the current connection address
Socket.binaryType Get the data type of the transfer

WebSocket life cycle

life cycle describe
Socket.onopen  Triggered when a connection is established
Socket.onmessage Triggered when the client receives data from the server
Socket.onerror Triggered when a communication error occurs
Socket.onclose Fired when the connection is closed

// 设定默认值
var websock = null;

// 每10分钟 通过 websocket 向服务器发送一次心跳 证明客户端没有离线 依然在线可以正常接受消息
setInterval(this.websocketsend, 100000);


initWebsocket() {
    /*
    * 初始化 websock
    * 连接 服务器地址
    * 并绑定 websock 四个事件方法
    */
    this.websock = new WebSocket('ws://localhost:8080?userId=1');
    // 接收服务器返回的数据
    this.websock.onmessage = this.websocketonmessage;
    // 连接建立时触发
    this.websock.onopen = this.websocketonopen;
    // 连接中发生异常
    this.websock.onerror = this.websocketonerror;
    // 连接关闭时触发
    this.websock.onclose = this.websocketclose;
}


websocketonopen() {
    /*
    * websocket 初始化后 执行的方法
    * 调用 发送数据方法    
    */
    this.websocketsend();
},


websocketonerror() {
    /*
    * websocket 连接建立失败 执行的方法
    * 注:我这里加了个判断,如果联系建立失败就在连接几次
    */
    if(this.cishu < 5){
        this.cishu = this.cishu + 1;
        this.initWebsocket();
    }
},


websocketsend() {
    
    /*
    * websocket 数据发送 通过 websock.send() 方法向服务器发送数据
    * 注:这里随便发哈,主要作用就是通过这个动作,让客户端与服务端建立联系
    */
    let actions = {
        "test": "12345"
    };
    this.websock.send(JSON.stringify(actions));
},


websocketclose(e) { 
    /*
    * websocket 连接关闭 执行的方法
    */
    console.log('断开连接', e);
},


websocketonmessage(e) {
    /*
    * websocket 数据接收 执行的方法
    * 注:服务器通过 websocke 向客户端发送数据时,这里的方法就会自动触发啦
    */
    const redata = JSON.parse(e.data);
    switch (redata.messageType) {
        case 0: // 售后 提示
        // ... 执行
        break;
        case 1: // 库存 提示
        // ... 执行
        break;
        case 2: // 下架 提示
        // ... 执行
        break;
    }
},


Guess you like

Origin blog.csdn.net/weixin_43221910/article/details/123642418