微信小程序实时聊天WebSocket

发布时间:2020-09-07 23:53:18 作者:a_靖
来源:脚本之家 阅读:231

本文实例为大家分享了微信小程序实时聊天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>

微信小程序实时聊天WebSocket

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持亿速云。

推荐阅读:
  1. 微信小程序中GoEasy实现websocket实时通讯的方法
  2. 微信小程序websocket实现即时聊天功能

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

微信小程序 聊天 websocket

上一篇:js实现登录拖拽窗口

下一篇:Python爬虫信息输入及页面的切换方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》