uni-app快速入手 ——(11)uni-app如何简单快速使用websocket

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 17:51   2574   0

第一步创建一个websocket.js

import variable from './variable.js'//ws长连接...

var connect = function(userId) {
 uni.connectSocket({
  url: variable.socketUrl + userId
 });
 uni.onSocketOpen(function(res) {
  console.log('WebSocket连接已打开!');
 });
 uni.onSocketError(function(res) {
  console.log('WebSocket连接打开失败,请检查!');
 });
 uni.onSocketMessage(function (res) {
   console.log('收到服务器内容:' + res.data);
        
//监听推送消息作出对应响应
   let noticeType = JSON.parse(res.data).noticeType
   if(noticeType == 'message_change'){
     uni.$emit('has-new-masg')
   }else if(noticeType == 'bd_rescue_alarm'){
    uni.$emit('sos-pop-alarm',{
     alarms:JSON.parse(res.data).noticeInfo
    })
   }
 });
 uni.onSocketClose(function (res) {
   console.log('WebSocket 已关闭!');
//监听断开重连
   uni.$emit('websocket-close')
 });
}

var closeSocket = function(){
  uni.closeSocket();
}

module.exports = {
 connectSocket:connect,
 closeSocket:closeSocket
}

在index.vue中使用

import socket from '@/utils/websocket.js'

onLoad() {
   let that = this;

   if (that.hasLogin) {
    console.log("用户信息-------------", that.userInfo)
    // 连接socket
    socket.connectSocket(that.userInfo.openid)
    uni.$on('websocket-close', res => {
     console.log("websoket连接断开重新连接", res)
     socket.connectSocket(that.userInfo.openid)
    })
   }

   uni.$on('has-new-masg', res => {
    console.log("websoket已经连接推送======消息推送")
    
   })
   // sos求救推送
   uni.$on('sos-pop-alarm', res => {
    console.log("websoket已经连接推送======消息推送", res.alarms)
    
   })
   
   

  },

简单的socket就可以了

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP