Initial experience of wechat applet webSocket

WebSocket is a single TCP Connect to full duplex Communication protocol. WebSocket communication protocol was approved by IETF As standard RFC 6455 and supplemented by RFC7936. WebSocket API Also be W3C Set as standard.
WebSocket makes the data exchange between the client and the server easier, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete one handshake, and they can directly create a persistent connection and carry out two-way data transmission.

Today, I will briefly explain how to use webSocket of wechat applet:

Wechat websocket API Express

The following webSocket is my own use of WeChat small program api to write some steps to encapsulate, mainly the realization of small program ends, truly realize the webSocket project also needs support from the backstage personnel.

In an applet, you can start a websocket connection in the onLoad method and close the connection in onHide.

var sotk = null;
var socketOpen = false;
var wsbasePath = "ws://Developer server wss interface address/“;

//start websoket
  webSocketStart(e){
    sotk = wx.connectSocket({
      url: wsbasePath,
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: "POST",
      success: res => {
        console.log('Applet connected successfully:', res);
      },
      fail: err => {
        console.log('Something went wrong!!' + err);
        wx.showToast({
          title: 'Network exception!',
        })
      }
    })

    this.webSokcketMethods();

  },

//Monitor command
  webSokcketMethods(e){
    let that = this;
    sotk.onOpen(res => {
      socketOpen = true;
      console.log('Monitor WebSocket Connection open event.', res);
    })
    sotk.onClose(onClose => {
      console.log('Monitor WebSocket Connection close event.', onClose)
      socketOpen = false;
    })
    sotk.onError(onError => {
      console.log('Monitor WebSocket Mistake. error message', onError)
      socketOpen = false
    })

    sotk.onMessage(onMessage => {
      var data = JSON.parse(onMessage.data);
      console.log('Monitor WebSocket Message event received to the server. Messages returned by the server',data);
     
    })
   
  },

//send message
  sendSocketMessage(msg) {
    let that = this;
    if (socketOpen){
      console.log('adopt WebSocket Connect to send data', JSON.stringify(msg))
      sotk.send({
        data: JSON.stringify(msg)
      }, function (res) {
        console.log('has been sent', res)
      })
    }
    
  },
 //Close connection
  closeWebsocket(str){
    if (socketOpen) {
      sotk.close(
        {
          code: "1000",
          reason: str,
          success: function () {
            console.log("Close successfully websocket Connect");
          }
        }
      )
    }
  },

 

Keywords: PHP JSON network

Added by ceruleansin on Wed, 23 Oct 2019 19:39:05 +0300