本文實例為大家分享了微信小程序實時聊天WebSocket的具體代碼,供大家參考,具體內容如下
1.所有監聽事件先在onload監聽。
// 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 () { // 創建Socket SocketTask = wx.connectSocket({ url: url, data: 'data', header: { 'content-type': 'application/json' }, method: 'post', success: function (res) { console.log('WebSocket連接創建', res) }, fail: function (err) { wx.showToast({ title: '網絡異常!', }) console.log(err) }, }) if (SocketTask) { SocketTask.onOpen(res => { console.log('監聽 WebSocket 連接打開事件。', res) }) SocketTask.onClose(onClose => { console.log('監聽 WebSocket 連接關閉事件。', onClose) }) SocketTask.onError(onError => { console.log('監聽 WebSocket 錯誤。錯誤信息', onError) }) SocketTask.onMessage(onMessage => { console.log('監聽WebSocket接受到服務器的消息事件。服務器返回的消息', 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就發送數據給服務器 sendSocketMessage(data) } }, bindKeyInput: function (e) { this.setData({ inputValue: e.detail.value }) }, onHide: function () { SocketTask.close(function (close) { console.log('關閉 WebSocket 連接。', close) }) },}) //通過 WebSocket 連接發送數據,需要先 wx.connectSocket,并在 wx.onSocketOpen 回調之后才能發送。function sendSocketMessage(data) { console.log('通過 WebSocket 連接發送數據') if (socketOpen) { SocketTask.send({data: JSON.stringify(data) }, function (res) { console.log('已發送', res) }) } else { socketMsgQueue.push(msg) }}
html
<input type="text" bindinput="bindKeyInput" value='{{inputValue}}' placeholder="" /><button bindtap="submitTo" class='user_input_text'>發送</button>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VEVB武林網。
新聞熱點
疑難解答