stomp.js
1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import SockJS from 'sockjs-client'
import Stomp from 'webstomp-client'
let stompClient = null
const getStompClient = function () {
if (stompClient === null) {
let socket = new SockJS('https://openday.console.etoneiot.tech/openday-boot/realtime')
stompClient = Stomp.over(socket)
stompClient.hasDebug = false
}
return stompClient
}
/**
* 连接服务
* @param [{ topic: String, callback: Function}]
*/
const connect = function (params) {
let client = getStompClient()
if (client.connected) {
return
}
let onConnected = function (frame) {
for (const param of params) {
if (!param.type) {
param.type = 'subscribe'
}
if (param.type === 'subscribe') {
client.subscribe(param.topic, param.callback)
}
if (param.type === 'send') {
if (!param.payload) {
param.payload = ""
}
client.send(param.topic, param.payload)
}
if (param.type === 'callback' && param.callback) {
param.callback(client)
}
}
}
client.connect({}, onConnected, (frame) => {
//自动重连
setTimeout(() => {
let socket = new SockJS('/openday-boot/realtime')
stompClient = Stomp.over(socket)
stompClient.hasDebug = false
connect(params)
}, 2000)
})
}
const disconnect = function () {
if (stompClient && stompClient.connected) {
stompClient.disconnect()
stompClient = null
}
}
const sendMessage = function (topic, message) {
if (stompClient && stompClient.connected) {
let msg = message
if (typeof msg !== 'string') {
msg = JSON.stringify(msg)
}
stompClient.send(topic, msg)
} else {
throw 'stomp client is null or disconnected'
}
}
export default {
connect,
disconnect,
sendMessage
}