current position:Home>Front end websocket usage

Front end websocket usage

2021-08-23 02:06:43 CUI_ PING

1. structure WebSocket example

var ws = new WebSocket('ws://localhost:8080');

2. Of the current instance readyState state

WebSocket Four states 
CONNECTING: The value is 0, Means connecting .
OPEN: The value is 1, Indicates successful connection , I can communicate with you .
CLOSING: The value is 2, Indicates that the connection is closing .
CLOSED: The value is 3, Indicates that the connection has been closed , Or the connection fails to open .

3. Instance property callback function

ws.onopen = (e)=> {
  console.log(" Successful connection ")
}
ws.onmessage= (e)=> {
  console.log(" Message received successfully ")
}
ws.onoerror = (e)=> {
  console.log(" The connection fails ")
}
ws.onclose = (e)=> {
  console.log(" Connection is closed ")
}

4. Reconnection

 // Reconnection 
  reConnection(){
    console.log(" Reconnect the ")
    if(this.lockReconnect){
      return
    }
    this.lockReconnect = true
    if(this.timerReconnect) {
      clearTimeout(this.timerReconnect)
    } 

    // If you don't connect, you'll always reconnect ,  Set delay , Avoid asking too many 
    this.timerReconnect = setTimeout(() => { //setTimeout  It's time to execute 
      this.createWebSocket()
      this.lockReconnect = false
    }, 5000);
    
  }

5. Monitor your heartbeat

heartCheck(){
    console.log(" Monitor your heartbeat ")
    if(this.timerHeart){
      clearTimeout(this.timerHeart)
    }

    if(this.timerServerHeart){
      clearTimeout(this.timerServerHeart)
    }

    this.timerHeart = setTimeout(() => {
      this.ws.send("are you weak")

      this.timerServerHeart = setTimeout(() => {
        //  Broken 
        this.ws.close()
      }, 5000);

      this.lockReconnect = false
    }, 2000);

  }

6. Complete package code ——— Update after improvement

copyright notice
author[CUI_ PING],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210823020640724s.html

Random recommended