最近早做一个外卖的小程序,碰到一个需求,多人下单,为了保证堂食同桌的每个人实时获取到每个人点菜信息,所以使用websocket,小程序也提供了socket的API。
自己封装的socket.io.js文件:
const callback=()=>{};
const initSocket=(option={})=>{
const { websocket_url, websocket_token } = option;
const socketTask= wx.connectSocket({
url: websocket_url,
success: function (res) {
console.log(res);
},
fail: function (fail) {
console.log(fail);
}
});
// 发送token
wx.onSocketOpen(function () {
wx.sendSocketMessage({
data: websocket_token,
})
})
wx.onSocketError(function (res) {
console.log('WebSocket连接打开失败,请检查!')
})
// 接收推送
return socketTask;
}
function resiverMessage(context) {
wx.onSocketMessage(function (dat