国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

微信小程序實時聊天WebSocket

2019-11-19 13:32:53
字體:
來源:轉載
供稿:網友

本文實例為大家分享了微信小程序實時聊天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>

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 保定市| 教育| 长岛县| 沙河市| 汾阳市| 聂荣县| 巴彦县| 水富县| 朝阳市| 兴山县| 霍城县| 伊通| 左云县| 苍南县| 安丘市| 永康市| 阜宁县| 凤台县| 都兰县| 荥经县| 株洲县| 仙游县| 临西县| 永川市| 鲁山县| 神木县| 广昌县| 和政县| 马鞍山市| 宝兴县| 西畴县| 阿拉善右旗| 天门市| 兴仁县| 五峰| 东方市| 东阳市| 清远市| 怀来县| 禹城市| 且末县|