今天簡單講解下微信小程序的webSocket如何使用:html
如下webSocket是本人使用微信小程序api寫的一些步驟封裝,主要是小程序端的實現,真正實現webSocket項目還要後臺人員的給力支持。小程序
小程序中,能夠在onLoad方法開始一個webSoket鏈接,在onHide時關閉鏈接。微信小程序
var sotk = null; var socketOpen = false; var wsbasePath = "ws://開發者服務器 wss 接口地址/"; //開始webSocket webSocketStart(e){ sotk = wx.connectSocket({ url: wsbasePath, header: { 'content-type': 'application/x-www-form-urlencoded' }, method: "POST", success: res => { console.log('小程序鏈接成功:', res); }, fail: err => { console.log('出現錯誤啦!!' + err); wx.showToast({ title: '網絡異常!', }) } }) this.webSokcketMethods(); }, //監聽指令 webSokcketMethods(e){ let that = this; sotk.onOpen(res => { socketOpen = true; console.log('監聽 WebSocket 鏈接打開事件。', res); }) sotk.onClose(onClose => { console.log('監聽 WebSocket 鏈接關閉事件。', onClose) socketOpen = false; }) sotk.onError(onError => { console.log('監聽 WebSocket 錯誤。錯誤信息', onError) socketOpen = false }) sotk.onMessage(onMessage => { var data = JSON.parse(onMessage.data); console.log('監聽WebSocket接受到服務器的消息事件。服務器返回的消息',data); }) }, //發送消息 sendSocketMessage(msg) { let that = this; if (socketOpen){ console.log('經過 WebSocket 鏈接發送數據', JSON.stringify(msg)) sotk.send({ data: JSON.stringify(msg) }, function (res) { console.log('已發送', res) }) } }, //關閉鏈接 closeWebsocket(str){ if (socketOpen) { sotk.close( { code: "1000", reason: str, success: function () { console.log("成功關閉websocket鏈接"); } } ) } },