本文實(shí)例為大家分享了微信小程序?qū)崟r(shí)聊天WebSocket的具體代碼,供大家參考,具體內(nèi)容如下
1.所有監(jiān)聽事件先在onload監(jiān)聽。
// pages/index/to_news/to_news.js var app = getApp(); var socketOpen = false; var SocketTask = false; var url = 'ws://192.168.0.120:7011'; Page({ data: { inputValue: '', returnValue: '', }, onLoad: function (options) { }, onReady: function () { // 創(chuàng)建Socket SocketTask = wx.connectSocket({ url: url, data: 'data', header: { 'content-type': 'application/json' }, method: 'post', success: function (res) { console.log('WebSocket連接創(chuàng)建', res) }, fail: function (err) { wx.showToast({ title: '網(wǎng)絡(luò)異常!', }) console.log(err) }, }) if (SocketTask) { SocketTask.onOpen(res => { console.log('監(jiān)聽 WebSocket 連接打開事件。', res) }) SocketTask.onClose(onClose => { console.log('監(jiān)聽 WebSocket 連接關(guān)閉事件。', onClose) }) SocketTask.onError(onError => { console.log('監(jiān)聽 WebSocket 錯(cuò)誤。錯(cuò)誤信息', onError) }) SocketTask.onMessage(onMessage => { console.log('監(jiān)聽WebSocket接受到服務(wù)器的消息事件。服務(wù)器返回的消息', onMessage) }) } }, // 提交文字 submitTo: function (e) { let that = this; that.data.allContentList.push({that.data.inputValue }); that.setData({ allContentList: that.data.allContentList }) var data = { text: that.data.inputValue } if (socketOpen) { // 如果打開了socket就發(fā)送數(shù)據(jù)給服務(wù)器 sendSocketMessage(data) } }, bindKeyInput: function (e) { this.setData({ inputValue: e.detail.value }) }, onHide: function () { SocketTask.close(function (close) { console.log('關(guān)閉 WebSocket 連接。', close) }) }, }) //通過 WebSocket 連接發(fā)送數(shù)據(jù),需要先 wx.connectSocket,并在 wx.onSocketOpen 回調(diào)之后才能發(fā)送。 function sendSocketMessage(data) { console.log('通過 WebSocket 連接發(fā)送數(shù)據(jù)') if (socketOpen) { SocketTask.send({data: JSON.stringify(data) }, function (res) { console.log('已發(fā)送', res) }) } else { socketMsgQueue.push(msg) } }
html
<input type="text" bindinput="bindKeyInput" value='{{inputValue}}' placeholder="" /> <button bindtap="submitTo" class='user_input_text'>發(fā)送</button>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com