>  기사  >  위챗 애플릿  >  WeChat 애플릿 SocketIO 인스턴스 구문 분석

WeChat 애플릿 SocketIO 인스턴스 구문 분석

高洛峰
高洛峰원래의
2017-03-31 14:01:193431검색

이 글은 주로 WeChat 애플릿 SocketIO의 관련 정보를 소개합니다. 다음은 누구나 쉽게 참고할 수 있는 간단한 예입니다.

WeChat 애플릿 SocketIO의 간단한 예:

요즈음 좋은 사람들이 위챗 미니 프로그램을 만들고 있습니다. ScoketIO는 위챗의 네트워크 커뮤니케이션입니다. 여기서는 사용 방법과 주의할 점을 알려드리겠습니다. !

WeChat 애플릿의 SocketIO 구현은 CFETram 구현을 기반으로


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

를 개선합니다. 첨부된 프로젝트는 편리한 테스트를 위해 Scoket.IO 공식 데모 채팅방에 대한 액세스를 보여주는 WeChat 애플릿의 데모 프로젝트입니다. 자세한 사용법은 공식 문서를 참조하세요.

사용방법


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',
}

위 내용은 WeChat 애플릿 SocketIO 인스턴스 구문 분석의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.