简介:
本来使用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
javascript
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) {
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.connect(header, function () {
console.log('stomp connected')
resolve(client)
})
// 关闭连接
client.close = () =>{
uni.closeSocket()
}
})
},
sendMessage(message) {
if (socketOpen) {
uni.sendSocketMessage({
data: message,
})
} else {
socketMsgQueue.push(message)
}
},
}
3.监听+发送+关闭代码
javascript
//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()
},
// 离开页面是关闭连接
// 我的业务是仿微信这种,每次连接人不同,频繁建立新连接,根据自己需要决定什么时候关闭连接
onUnload(){
this.client && this.client.close()
},
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 })
);
},