⼩程序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) => {
this.isConnected = true;
//this.ping();
resolve(response);
});
if (this.isConnected) {
this.fire('error', error);
} else {
reject(error);
}
});
if (this.isConnected) {
this.fire('error', new Error("The websocket was closed by server"));
} else {
this.fire('close');
}
this.isConnected = false;
this.destory();
});
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.closeSocket();
} else {
reject(new Error('socket is not connected'));
}
});
}
emit(type, ...params) {
const data = [type, ...params];
wx.sendSocketMessage({
data: [ssage, events.EVENT, JSON.stringify(data)].join("")
});
}
destory() {
}
_handleMessage({ data }) {
const [match, packet, event, content] = /^(\d)(\d?)(.*)$/.exec(data);
if (+event === events.EVENT) {
switch (+packet) {
ssage:
let pack;
try {
pack = JSON.parse(content);
} catch (error) {
<('解析 ws 数据包失败:')
<(error);
}
const [type, ...params] = pack;
this.fire(type, ...params);
break;
}
}
else if (+packet == packets.pong) {
this.ping();
}
}
};
emitter.setup(WxSocketIO.prototype);
DEMO
项⽬附了⼀个⼩程序的DEMO 项⽬演⽰了接⼊ Scoket.IO 官⽅的演⽰聊天室,以便⽅便测试,关于详细⽤法还请参考官⽅⽂档。
How to use
socket编程聊天室基本流程const opts = {}
const socket = this.globalData.socket = new WxSocketIO()
.then(_ => {
console.info('App::WxSocketIO::onOpen')
console.info('App:onShow:', that.globalData)
})
.catch(err => {
<('App::WxSocketIO::onError', err)
})
其中t(ws_url, opts)中,opts⽬前可选值是path,⽤来指定使⽤socket.io时默认的path,⽐如设置opts为下列值:
{
query: 'fanweixiao',
with: 'mia&una',
}
感谢阅读,希望能帮助到⼤家,谢谢⼤家对本站的⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论