前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >通信系列 | Websocket在微信小程序的用法

通信系列 | Websocket在微信小程序的用法

作者头像
Tinywan
发布2021-01-28 10:21:10
3.9K0
发布2021-01-28 10:21:10
举报
文章被收录于专栏:开源技术小栈开源技术小栈

前言

使用Websocket的及时通讯实现直播间的评论、加入直播间、离开直播间、点赞、关注、商品上下架等操作。

什么是 WebSocket

WebSocket是一种通信协议,可在单个TCP连接上进行全双工通信。WebSocket使得客户端和服务器之间的数据交换变得更加简单,允许服务端主动向客户端推送数据。在WebSocket API中,浏览器和服务器只需要完成一次握手,两者之间就可以建立持久性的连接,并进行双向数据传输。

通信流程

典型的Websocket握手

客户端请求:

代码语言:javascript
复制
GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13

服务器响应

代码语言:javascript
复制
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat

字段说明

  • Connection必须设置Upgrade,表示客户端希望连接升级。
  • Upgrade字段必须设置Websocket,表示希望升级到Websocket协议。
  • Sec-WebSocket-Key是随机的字符串,服务器端会用这些数据来构造出一个SHA-1的信息摘要。把“Sec-WebSocket-Key”加上一个特殊字符串“258EAFA5-E914-47DA-95CA-C5AB0DC85B11”,然后计算SHA-1摘要,之后进行Base64编码,将结果做为“Sec-WebSocket-Accept”头的值,返回给客户端。如此操作,可以尽量避免普通HTTP请求被误认为Websocket协议。
  • Sec-WebSocket-Version 表示支持的Websocket版本。RFC6455要求使用的版本是13,之前草案的版本均应当弃用。
  • Origin字段是可选的,通常用来表示在浏览器中发起此Websocket连接所在的页面,类似于Referer。但是,与Referer不同的是,Origin只包含了协议和主机名称。其他一些定义在HTTP协议中的字段,如Cookie等,也可以在Websocket中使用。

Websocket API

  • wx.connectSocket:创建一个 WebSocket 连接 ;
  • sotk.onOpen:监听 WebSocket 连接打开事件 ;
  • sotk.onClose:监听 WebSocket 连接关闭事件 ;
  • sotk.onError:监听 WebSocket 错误事件 ;
  • sotk.onMessage:监听 WebSocket 接受到服务器的消息事件 ;(重要:负责监听接收数据)
  • sotk.send:通过 WebSocket 连接发送数据 。(重要:负责发送数据)

使用案例如下:

代码语言:javascript
复制
var sotk = null;
var socketOpen = false;
var wsbasePath = "ws://开发者服务器 wss 接口地址/";

//开始webSocket
  webSocketStart(e){
    sotk = wx.connectSocket({
      url: wsbasePath,
      success: res => {
        console.log('小程序连接成功:', res);
      },
      fail: err => {
        console.log('出现错误啦!!' + err);
        wx.showToast({
          title: '网络异常!',
        })
      }
    })

    this.webSokcketMethods();

  },

//监听指令
  webSokcketMethods(e){
    let that = this;
    sotk.onOpen(res => {
      socketOpen = true;
      console.log('监听 WebSocket 连接打开事件。', res);
    })
    sotk.onClose(onClose => {
      console.log('监听 WebSocket 连接关闭事件。', onClose)
      socketOpen = false;
    })
    sotk.onError(onError => {
      console.log('监听 WebSocket 错误。错误信息', onError)
      socketOpen = false
    })

    sotk.onMessage(onMessage => {
      var data = JSON.parse(onMessage.data);
      console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息',data);
     
    })
   
  },

//发送消息
  sendSocketMessage(msg) {
    let that = this;
    if (socketOpen){
      console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg))
      sotk.send({
        data: JSON.stringify(msg)
      }, function (res) {
        console.log('已发送', res)
      })
    }
    
  },
 //关闭连接
  closeWebsocket(str){
    if (socketOpen) {
      sotk.close(
        {
          code: "1000",
          reason: str,
          success: function () {
            console.log("成功关闭websocket连接");
          }
        }
      )
    }
  },

实现逻辑

1、通过onMessage监听收到的信息,接收到的信息会返回一个type值,通过type值判断接收到的数据是什么数据,之后分别进行处理、赋值即可。

2、通过sendSocketMessage发送数据,根据后端定义的字段发送请求,字段中也包含type值,告诉websocket是处理什么类型的值。

关键代码如下:

代码语言:javascript
复制
webSokcketMethods(e) {
    this.websocket.onMessage(onMessage => {
      console.log(this.data)
      var data = JSON.parse(onMessage.data);
      console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息', data);
      if (data.client_id) {
        this.setData({
          client_id: data.client_id
        })
      }
      if (data.msg_type === 'init') {
        this.joinLive()
      }
      if (data.msg_type === 'join') {
        wx.hideLoading()
        this.endtrain(data.msg_content)
        this.setData({
          is_join: true,
          lookNumber: data.online_num
        })
        if (data.message_list) {
          this.setData({
            commentList: data.message_list,
            toLast: 'item' + data.message_list.length,
            lookNumber: data.online_num,
            followNumber: data.subscribe_num
          })
        }

      }
      if (data.msg_type == 'message') {
        var commentItem = {
          name: data.from_name,
          content: data.content
        }
        var commentArr = this.data.commentList
        console.log(commentArr)
        commentArr.push(commentItem)
        this.setData({
          commentList: commentArr,
          toLast: 'item' + commentArr.length,
        })

        if (this.data.platform === 'android') {
          this.messageScroll()
        }
      }
      if (data.msg_type == 'subscribe') {
        this.setData({
          followNumber: data.subscribe_num
        })
        this.endtrain(data.msg_content)

      }

      if (data.msg_type == 'leave') {
        this.endtrain(data.msg_content)
      }

      if (data.msg_type == 'buy') {
        this.endtrain(data.msg_content)
      }
    })
  },
   // 加入直播间
  joinLive() {
    var data = {
      msg_type: 'join',
      room_id: this.data.liveRoomId,
      live_id: this.data.liveId,
      from_uid: this.data.anchorUid,
      client_id: this.data.client_id,
      is_anchor: true,
      from_name: this.data.anchorName
    }
    console.log('通过 WebSocket 连接发送数据', JSON.stringify(data))
    this.websocket.send({
      data: JSON.stringify(data),
      success: function (res) {
        console.log(res)
      },
      fail: function (err) {
        console.log(err)
      }
    })
  },
  // 商品上架
  goodsShelfOn(goodsId, goodsName, goodsPrice, defaultImage, status) {
    var data = {
      msg_type: 'on_off_shelf',
      room_id: this.data.liveRoomId,
      live_id: this.data.liveId,
      from_uid: this.data.anchorUid,
      client_id: this.data.client_id,
      from_name: this.data.anchorName,
      goods_id: goodsId,
      goods_name: goodsName,
      goods_price: goodsPrice,
      default_image: defaultImage,
      status: 'on'
    }
    console.log('通过 WebSocket 连接发送数据', JSON.stringify(data))
    this.websocket.send({
      data: JSON.stringify(data),
      success: function (res) {
        console.log(res)
      },
      fail: function (err) {
        console.log(err)
      }
    })
  }

心跳检测、断线重连

在实际应用中,需要不断判断websocket处于连接阶段。

wechat-websocket.js文件

代码语言:javascript
复制
export default class websocket {
  constructor({ heartCheck, isReconnection }) {
    // 是否连接
    this._isLogin = false;
    // 当前网络状态
    this._netWork = true;
    // 是否人为退出
    this._isClosed = false;
    // 心跳检测频率
    this._timeout = 3000;
    this._timeoutObj = null;
    // 当前重连次数
    this._connectNum = 0;
    // 心跳检测和断线重连开关,true为启用,false为关闭
    this._heartCheck = heartCheck;
    this._isReconnection = isReconnection;
    this._onSocketOpened();
  }
  // 心跳重置
  _reset() {
    clearTimeout(this._timeoutObj);
    return this;
  }
  // 心跳开始
  _start() {
    let _this = this;
    this._timeoutObj = setInterval(() => {
      wx.sendSocketMessage({
        // 心跳发送的信息应由前后端商量后决定
        data: JSON.stringify({
          "msg_type": 'ping'
        }),
        success(res) {
          console.log(res)
          console.log("发送心跳成功");
        },
        fail(err) {
          console.log(err)
          // wx.showToast({
          //   title: "websocket已断开",
          //   icon: 'none'
          // })
          _this._reset()
        }
      });
    }, this._timeout);
  }
  // 监听websocket连接关闭
  onSocketClosed(options) {
    wx.onSocketClose(err => {
      console.log('当前websocket连接已关闭,错误信息为:' + JSON.stringify(err));
      // 停止心跳连接
      if (this._heartCheck) {
        this._reset();
      }
      // 关闭已登录开关
      this._isLogin = false;
      // 检测是否是用户自己退出小程序
      console.log(this._isClosed)
      if (!this._isClosed) {
        // 进行重连
        if (this._isReconnection) {
          this._reConnect(options)
        }
      }
      
    })
  }
  // 检测网络变化
  onNetworkChange(options) {
    wx.onNetworkStatusChange(res => {
      console.log('当前网络状态:' + res.isConnected);
      if (!this._netWork) {
        this._isLogin = false;
        // 进行重连
        if (this._isReconnection) {
          this._reConnect(options)
        }
      }
    })
  }
  _onSocketOpened() {
    wx.onSocketOpen(res => {
      console.log('websocket已打开');
      // 打开已登录开关
      this._isLogin = true;
      // 发送心跳
      if (this._heartCheck) {
        this._reset()._start();
      }
      // 发送登录信息
      wx.sendSocketMessage({
        // 这里是第一次建立连接所发送的信息,应由前后端商量后决定
        data: JSON.stringify({
          "key": 'value'
        })
      })
      // 打开网络开关
      this._netWork = true;
    })
  }
  // 接收服务器返回的消息
  onReceivedMsg(callBack) {
    wx.onSocketMessage(msg => {
      if (typeof callBack == "function") {
        callBack(msg)
      } else {
        console.log('参数的类型必须为函数')
      }
    })
  }
 
  // 建立websocket连接
  initWebSocket(options) {
    let _this = this;
    if (this._isLogin) {
      console.log("您已经登录了");
    } else {
      console.log('未登录')
      // 检查网络
      wx.getNetworkType({
        success(result) {
          if (result.networkType != 'none') {
            console.log(result.networkType)
            // 开始建立连接
            wx.connectSocket({
              url: options.url,
              success(res) {
                if (typeof options.success == "function") {
                  options.success(res)
                } else {
                  console.log('参数的类型必须为函数')
                }
              },
              fail(err) {
                if (typeof options.fail == "function") {
                  options.fail(err)
                } else {
                  console.log('参数的类型必须为函数')
                }
              }
            })
          } else {
            console.log('网络已断开');
            _this._netWork = false;
            // 网络断开后显示model
            wx.showModal({
              title: '网络错误',
              content: '请重新打开网络',
              showCancel: false,
              success: function (res) {
                if (res.confirm) {
                  console.log('用户点击确定')
                }
              }
            })
          }
        }
      })
    }
  }
  // 发送websocket消息
  sendWebSocketMsg(options) {
    wx.sendSocketMessage({
      data: options.data,
      success(res) {
        if (typeof options.success == "function") {
          options.success(res)
        } else {
          console.log('参数的类型必须为函数')
        }
      },
      fail(err) {
        if (typeof options.fail == "function") {
          options.fail(err)
        } else {
          console.log('参数的类型必须为函数')
        }
      }
    })
  }
  // 重连方法,会根据时间频率越来越慢
  _reConnect(options) {
    let timer, _this = this;
    if (this._connectNum < 20) {
      timer = setTimeout(() => {
        this.initWebSocket(options)
      }, 3000)
      this._connectNum += 1;
    } else if (this._connectNum < 50) {
      timer = setTimeout(() => {
        this.initWebSocket(options)
      }, 10000)
      this._connectNum += 1;
    } else {
      timer = setTimeout(() => {
        this.initWebSocket(options)
      }, 450000)
      this._connectNum += 1;
    }
  }
  // 关闭websocket连接
  closeWebSocket(){
    wx.closeSocket();
    this._isClosed = true;
  }
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-01-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 万少波的播客 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 前言
  • 什么是 WebSocket
  • 通信流程
  • 典型的Websocket握手
    • 客户端请求:
      • 服务器响应
        • 字段说明
        • Websocket API
        • 实现逻辑
        • 心跳检测、断线重连
        相关产品与服务
        云直播
        云直播(Cloud Streaming Services,CSS)为您提供极速、稳定、专业的云端直播处理服务,根据业务的不同直播场景需求,云直播提供了标准直播、快直播、云导播台三种服务,分别针对大规模实时观看、超低延时直播、便捷云端导播的场景,配合腾讯云视立方·直播 SDK,为您提供一站式的音视频直播解决方案。
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档