小程序使用webstocket

nginx配置 

location /wss {
     proxy_pass http://websocket;
     proxy_http_version 1.1;
     proxy_set_header Upgrade $http_upgrade;
     proxy_set_header Connection "Upgrade";
}

小程序端 

onLoad: function (options) {
    let that = this
    this.data.id = options.id

    this.gettoutong_info()

    console.log(this.data.ddd)
    var socketOpen = false
    var socketMsgQueue = []
    wx.connectSocket({
      url: 'wss://hr.18ycg.com/wss/'
    })

    wx.onSocketOpen(function (res) {
      socketOpen = true
      var user_info = wx.getStorageSync('userinfo')
      var user_info = wx.getStorageSync('userinfo')
      var data = { 'group': 'users', 'uid': user_info.user_id };
      sendSocketMessage(JSON.stringify(data))
    })
    wx.onSocketMessage(function (res) {
     let resc = JSON.parse(res.data)
      let message = { from: that.data.to_uid, to: that.data.uid, message: resc.message, sent: resc.sent}
      let messages = that.data.messages
      messages.push(message)
      that.setData({
        messages:messages,
        scrollTop: 768 + 50
      })
    })

    function sendSocketMessage(msg) {
      if (socketOpen) {
        wx.sendSocketMessage({
          data: msg
        })
      } else {
        socketMsgQueue.push(msg)
      }
    }
  },
  sends: function () {
    let message= this.data.message
    this.setData({
      message:''
    })
    return false
    var that = this;
    wx.request({
      url: app.globalData.URL + "/wapmember/ltserver",
      data: {
        message: message,
        uid:that.data.uid,
        to_uid:that.data.to_uid
      },
      header: {
        'content-type': 'application/json', // 默认值
        'Cookie': wx.getStorageSync('sessionkey')
      },
      success: function (res) {
        var message = res.data.data
        var messages = that.data.messages
        messages.push(message)

      
        that.setData({
          messages: messages,
          message:'',
          scrollTop: 768+50
        });
      }
    })
  },

 

 

发布了27 篇原创文章 · 获赞 4 · 访问量 4万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览