快速上手微信小程序webSocket

WebSocket是一種在單個 TCP鏈接上進行 全雙工通訊的協議。WebSocket通訊協議於2011年被 IETF定爲標準RFC 6455,並由RFC7936補充規範。WebSocket  API也被 W3C定爲標準。
WebSocket使得客戶端和服務器之間的數據交換變得更加簡單,容許服務端主動向客戶端推送數據。在WebSocket API中,瀏覽器和服務器只須要完成一次握手,二者之間就直接能夠建立持久性的鏈接,並進行雙向數據傳輸。

今天簡單講解下微信小程序的webSocket如何使用:html

微信webSocketAPI直通車web

如下webSocket是本人使用微信小程序api寫的一些步驟封裝,主要是小程序端的實現,真正實現webSocket項目還要後臺人員的給力支持。小程序

小程序中,能夠在onLoad方法開始一個webSoket鏈接,在onHide時關閉鏈接。微信小程序

var sotk = null;
var socketOpen = false;
var wsbasePath = "ws://開發者服務器 wss 接口地址/";

//開始webSocket
  webSocketStart(e){
    sotk = wx.connectSocket({
      url: wsbasePath,
      header: { 'content-type': 'application/x-www-form-urlencoded' },
      method: "POST",
      success: res => {
        console.log('小程序鏈接成功:', res);
      },
      fail: err => {
        console.log('出現錯誤啦!!' + err);
        wx.showToast({
          title: '網絡異常!',
        })
      }
    })

    this.webSokcketMethods();

  },

//監聽指令
  webSokcketMethods(e){
    let that = this;
    sotk.onOpen(res => {
      socketOpen = true;
      console.log('監聽 WebSocket 鏈接打開事件。', res);
    })
    sotk.onClose(onClose => {
      console.log('監聽 WebSocket 鏈接關閉事件。', onClose)
      socketOpen = false;
    })
    sotk.onError(onError => {
      console.log('監聽 WebSocket 錯誤。錯誤信息', onError)
      socketOpen = false
    })

    sotk.onMessage(onMessage => {
      var data = JSON.parse(onMessage.data);
      console.log('監聽WebSocket接受到服務器的消息事件。服務器返回的消息',data);
     
    })
   
  },

//發送消息
  sendSocketMessage(msg) {
    let that = this;
    if (socketOpen){
      console.log('經過 WebSocket 鏈接發送數據', JSON.stringify(msg))
      sotk.send({
        data: JSON.stringify(msg)
      }, function (res) {
        console.log('已發送', res)
      })
    }
    
  },
 //關閉鏈接
  closeWebsocket(str){
    if (socketOpen) {
      sotk.close(
        {
          code: "1000",
          reason: str,
          success: function () {
            console.log("成功關閉websocket鏈接");
          }
        }
      )
    }
  },
相關文章
相關標籤/搜索