Home  >  Article  >  WeChat Applet  >  Parsing WeChat applet SocketIO instance

Parsing WeChat applet SocketIO instance

高洛峰
高洛峰Original
2017-03-31 14:01:193430browse

This article mainly introduces the relevant information of the WeChat applet SocketIO. Here is a simple example for everyone. Friends in need can refer to it

Simple example of the WeChat applet SocketIO:

Nowadays, good people are working on WeChat mini programs. ScoketIO is the network communication of WeChat. Its importance is self-evident. Here I will tell you how to use it and what to pay attention to!

SocketIO implementation of WeChat applet, based on the implementation of CFETram, improve the


const emitter = require('./emitter.js');

/** socket.io 协议常量 */
var packets = {
  open:   0  // non-ws
 , close:  1  // non-ws
 , ping:   2
 , pong:   3
 , message: 4
 , upgrade: 5
 , noop:   6
};
var events = { 
  CONNECT: 0,
  DISCONNECT: 1,
  EVENT: 2,
  ACK: 3,
  ERROR: 4,
  BINARY_EVENT: 5,
  BINARY_ACK: 6
};

const PING_CHECK_INTERVAL = 2000;


class WxSocketIO {
  connect(url) {
    return new Promise((resolve, reject) => {
      wx.onSocketOpen((response) => {
        this.isConnected = true;
        //this.ping();
        resolve(response);
      });
      wx.onSocketError(error => {
        if (this.isConnected) {
          this.fire('error', error);
        } else {
          reject(error);
        }
      });
      wx.onSocketMessage(message => this._handleMessage(message));
      wx.onSocketClose(result => {
        if (this.isConnected) {
          this.fire('error', new Error("The websocket was closed by server"));
        } else {
          this.fire('close');
        }
        this.isConnected = false;
        this.destory();
      });
      wx.connectSocket({
        url: `${url}/?EIO=3&transport=websocket`
      });
    });
  }
  ping() {
    setTimeout(() => {
      if (!this.isConnected) return;
      wx.sendSocketMessage({
        data: [packets.ping, 'probe'].join('')
      });
    }, PING_CHECK_INTERVAL);
  }
  close() {
    return new Promise((resolve, reject) => {
      if (this.isConnected) {
        this.isConnected = false;
        wx.onSocketClose(resolve);
        wx.closeSocket();
      } else {
        reject(new Error('socket is not connected'));
      }
    });
  }
  emit(type, ...params) {
    const data = [type, ...params];
    wx.sendSocketMessage({
      data: [packets.message, events.EVENT, JSON.stringify(data)].join("")
    });
  }
  destory() {
    this.removeAllListeners();
  }
  _handleMessage({ data }) {
    const [match, packet, event, content] = /^(\d)(\d?)(.*)$/.exec(data);
    if (+event === events.EVENT) {
      switch (+packet) {
        case packets.message:
          let pack;
          try {
            pack = JSON.parse(content);
          } catch (error) {
            console.error('解析 ws 数据包失败:')
            console.error(error);
          }
          const [type, ...params] = pack;
          this.fire(type, ...params);
          break;
      }
    }
    else if (+packet == packets.pong) {
      this.ping();
    }
  }
};

emitter.setup(WxSocketIO.prototype);

module.exports = WxSocketIO;

DEMO

project Attached is a DEMO project of a WeChat applet that demonstrates access to the Scoket.IO official demo chat room for convenient testing. Please refer to the official documentation for detailed usage.

How to use


const opts = {}
const socket = this.globalData.socket = new WxSocketIO()
socket.connect('ws://chat.socket.io', opts)
.then(_ => {
 console.info('App::WxSocketIO::onOpen')
 console.info('App:onShow:', that.globalData)
})
.catch(err => {
 console.error('App::WxSocketIO::onError', err)
})
其中socket.connect(ws_url, opts)中,opts目前可选值是path,用来指定使用socket.io时默认的path,比如设置opts为下列值:

{
 query: 'fanweixiao',
 with: 'mia&una',
}

The above is the detailed content of Parsing WeChat applet SocketIO instance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn