uniapp微信小程序使用stomp.js实现STOMP传输协议的实时聊天

简介:

stomp.js:原生微信小程序中使用
stomp.js:官网
stomp.js:GitHub

本来使用websocket,后端同事使用了stomp协议,导致前端也需要对应修改。
在这里插入图片描述

如何使用

1.yarn add stompjs
2.版本 “stompjs”: “^2.3.3”
3.在static/js中新建websocket.js,然后在需要使用的页面引入监听代码+发送代码即可

代码如下:

位置:项目/pages/static/js/websocket.js
1.websocket.js

import Stomp from 'stompjs'

let socketOpen = false
let socketMsgQueue = []

export default {
  client: null,
  init(url, header ,connectWS) {
    if (this.client) {
      return Promise.resolve(this.client)
    }

    return new Promise((resolve, reject) => {
      const ws = {
        send: this.sendMessage,
        onopen: null,
        onmessage: null,
      }

      uni.connectSocket({ url, header })

      uni.onSocketOpen(function (res) {
        console.log('WebSocket连接已打开!', res)

        socketOpen = true
        for (let i = 0; i < socketMsgQueue.length; i++) {
          ws.send(socketMsgQueue[i])
        }
        socketMsgQueue = []

        ws.onopen && ws.onopen()
      })

      uni.onSocketMessage(function (res) {
        // ios 缺少 0x00 导致解析失败
        if (res && res.data) {
          let value = res.data;
          let code = value.charCodeAt(value.length - 1);
          if (code !== 0x00) {
            value += String.fromCharCode(0x00);
            res.data = value;
          }
        }
        ws.onmessage && ws.onmessage(res)
      })

      uni.onSocketError(function (res) {
        console.log('WebSocket 错误!', res)
      })

      uni.onSocketClose((res) => {
        this.client = null
        socketOpen = false
        console.log('WebSocket 已关闭!', res)
        if(res.code !== 1000){
          setTimeout(()=>{
            connectWS()
          },3000)
        }
      })

      Stomp.setInterval = function (interval, f) {
        return setInterval(f, interval)
      }
      Stomp.clearInterval = function (id) {
        return clearInterval(id)
      }

      const client = (this.client = Stomp.over(ws))
      // 关闭连接
      client.close = () =>{
        uni.closeSocket()
      }
      client.connect(header, function () {
        console.log('stomp connected')
        resolve(client)
      })
    })
  },
  sendMessage(message) {
    if (socketOpen) {
      uni.sendSocketMessage({
        data: message,
      })
    } else {
      socketMsgQueue.push(message)
    }
  },
}

2.监听+发送+关闭代码

//import WebSocket from "../../static/js/websocket"
import WebSocket from "@/static/js/websocket"
const app = getApp();
data: {
	objUid: '1',
	client: null,
	subscription: '',
	content: '发送的内容'
},
onLoad(options) {
	// stomp协议请求 
	this.initWS()
},
onShow() {
    // 切换任务后台,ws断开后重连
    if(!WebSocket.client){
        this.initWS()
    }
},
// 离开页面是关闭连接 
// 我的业务是仿微信这种,每次连接人不同,频繁建立新连接,根据自己需要决定什么时候关闭连接
onUnload(){
    this.client && this.client.close()
    // 直接关闭websocket
	// this.client && this.client.close()
	// 不关闭websocket连接,但是断开订阅
	// this.subscription && this.subscription.unsubscribe(this.subscription.id)
},
initWS() {
	WebSocket.init(
		`${app.globalData.WSURL}/chat`,
		// 传参
		{
			// login: 'admin',
			// passcode: 'admin',
		},
		// ws断开回调
		() => {
			this.initWS()
		}
	).then((client) => {
		this.client = client
		// 订阅
		this.subscription = client.subscribe(
			// 路径
			`/response/${app.globalData.uid}/${this.objUid}`,
			// 接收到的数据
			(res) => {
				console.log(res)
			},
			// 消息不会被确认接收,不确认每次连接都会推送
			// { ack: 'client' } 
		)
	})
},
// 直接调用发送即可
send() {
	this.client.send(
		// 路径
		`/child/${app.globalData.uid}/${this.objUid}`,
		// 自定义参数 http://jmesnil.net/stomp-websocket/doc/
		{},//priority: 9 
		// 发送文本
		JSON.stringify({ 'content': this.content })
	);
},

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘斩仙的笔记本

富贵险中求

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值