解析微信小程序SocketIO实例
- 微信应用
- 2024-10-14 13:42:02
解析微信小程序SocketIO实例
这篇文章主要介绍了微信小程序 SocketIO 的相关资料,这里给大家提供了一个简单实例,需要的朋友可以参考下
这篇文章主要介绍了微信小程序 SocketIO 的相关资料,这里给大家提供了一个简单实例,需要的朋友可以参考下
这篇文章主要介绍了微信小程序 socketio 的相关资料,这里给大家提供了一个简单实例,需要的朋友可以参考下
微信小程序 ScoketIO 简单实例:
现在好的人在搞微信小程序,ScoketIO 是微信的网络通信,它的重要性不言而喻,这里给大家讲讲如何使用以及注意事项!
微信小程序 的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;解析微信小程序SocketIO实例由讯客互联微信应用栏目发布,感谢您对讯客互联的认可,以及对我们原创作品以及文章的青睐,非常欢迎各位朋友分享到个人网站或者朋友圈,但转载请说明文章出处“解析微信小程序SocketIO实例”