简介:
原生微信小程序中使用
本来使用websocket,后端同事使用了stomp协议,导致前端也需要对应修改。
如何使用
1.yarn add stompjs
2.版本 “stompjs”: “^2.3.3”
3.在static/js中新建stomp.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,close: this.closeSocket,}uni.connectSocket({ url, header })uni.onSocketOpen(function (res) {console.log('WebSocket连接已打开!', res)socketOpen = truefor (let i = 0; i < socketMsgQueue.length; i++) {ws.send(socketMsgQueue[i])}socketMsgQueue = []ws.onopen && ws.onopen()})uni.onSocketMessage(function (res) {ws.onmessage && ws.onmessage(res)})uni.onSocketError(function (res) {console.log('WebSocket 错误!', res)})uni.onSocketClose((res) => {this.client.disconnect()this.client = nullsocketOpen = falseconsole.log('WebSocket 已关闭!', res)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.connect(header, function () {console.log('stomp connected')resolve(client)})})},disconnect() {uni.closeSocket()},sendMessage(message) {if (socketOpen) {uni.sendSocketMessage({data: message,})} else {socketMsgQueue.push(message)}},closeSocket() {console.log('closeSocket')},
}
3.监听+发送代码
//import WebSocket from "../../static/js/websocket"
import WebSocket from "@/static/js/websocket"
const app = getApp();
data: {objUid: '1',client: null,content: '发送的内容'
},
onLoad(options) {// stomp协议请求 this.initWS()
},
initWS() {WebSocket.init(`${app.globalData.WSURL}/chat`,// 传参{// login: 'admin',// passcode: 'admin',},// ws断开回调() => {this.initWS()}).then((client) => {this.client = client// 订阅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 }));
},