微信小程序使用Socket注意事項(xiàng)及實(shí)例
首先,一個(gè)小程序同時(shí)只能有一個(gè)WebSocket連接,如果當(dāng)前已經(jīng)存在一個(gè)WebSocket連接,會(huì)關(guān)閉當(dāng)前連接,并重新建立一個(gè)連接。
其次,如果使用了appID,協(xié)議必須是 wss://...
最近團(tuán)隊(duì)用小程序做行情,在連接socket的時(shí)候,發(fā)現(xiàn)在還沒(méi)有進(jìn)行subscribe的情況下,就直接進(jìn)行了廣播,并且自動(dòng)關(guān)閉了socket連接,
時(shí)間緊迫,抓耳撓腮,遂引用了socket-io(基于小程序的websocket仿寫(xiě)的socket-io,并非官方的socket-io,傳送門(mén)),使用方法:
1、先在utils文件夾粘貼一個(gè)io的js
2、然后 npm install wxapp-socket-io
3、config文件夾下新建一個(gè)socket.js,對(duì)socket連接進(jìn)行封裝,如下:
-
const io = require('../utils/io.js')
-
let url = 'wss://......'
-
let wsStatus = false
-
let onSocket = null
-
export const connect = function(cb){
-
if(!onSocket){
-
onSocket = io(url)
-
onSocket.on('connect', function (res) {
-
cb(true,onSocket)
-
wsStatus = true
-
})
-
setTimeout(function(){
-
if(!wsStatus){
-
cb(false,onSocket)
-
}
-
},10000)
-
}else{
-
cb(true,onSocket)
-
}
-
}
4、在要引用的頁(yè)面調(diào)用,全局封裝訂閱方法
-
let openSocket = require('../../config/socket')
-
let app = getApp()
-
let socket = null
-
Page({
-
data: {
-
zl: [[422, 400, 468, 834, 785, 446, 845, 517, 630, 797, 890, 529, 553, 425, 469, 470, 837, 841, 521, 525], [422, 400, 468, 834, 785, 446, 845, 517, 630, 797, 890, 529, 553, 425, 469, 470, 837, 841, 521, 525]]
-
},
-
onLoad: function () {
-
let that = this;
-
//socket調(diào)用
-
openSocket.connect(function (status, ws) {
-
if (status) {
-
socket = ws
-
this.subscribe('zl')//對(duì)封裝好對(duì)訂閱方法進(jìn)行調(diào)用
-
socket.on('broadcast', function (msg) {//廣播
-
console.log("broadcast");
-
console.log(msg);
-
})
-
} else {
-
alert("socket 連接失敗")
-
}
-
});
-
},
-
subscribe: function (type) {
-
if (socket) {
-
let eis = this.data[type]
-
if (eis && eis.length > 0) {
-
let param = {//僅供參考,根據(jù)接口自行更改
-
eis: eis.join(',')
-
}
-
socket.emit('subscribe', JSON.stringify(param));
-
}
-
}
-
}
-
});