微信小程序 ScoketIO 簡(jiǎn)單實(shí)例:
現(xiàn)在好的人在搞微信小程序,ScoketIO 是微信的網(wǎng)絡(luò)通信,它的重要性不言而喻,這里給大家講講如何使用以及注意事項(xiàng)!
微信小程序 的SocketIO 實(shí)現(xiàn),基于CFETram 的實(shí)現(xiàn)基礎(chǔ)上完善
const emitter = require('./emitter.js');/** socket.io 協(xié)議常量 */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 數(shù)據(jù)包失?。?) 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
項(xiàng)目附了一個(gè)微信小程序的DEMO 項(xiàng)目演示了接入 Scoket.IO 官方的演示聊天室,以便方便測(cè)試,關(guān)于詳細(xì)用法還請(qǐng)參考官方文檔。
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,用來(lái)指定使用socket.io時(shí)默認(rèn)的path,比如設(shè)置opts為下列值:{ query: 'fanweixiao', with: 'mia&una',}完整實(shí)例地址:https://github.com/fanweixiao/wxapp-socket-io
感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注