lemo-crm/web/app/services/websocket.js
2022-06-23 17:29:32 +08:00

88 lines
2.9 KiB
JavaScript

import Service from '@ember/service';
import { inject as service } from '@ember/service';
import $ from 'jquery';
export default Service.extend({
ajax: service('ajax'),
connect() {
const me = this;
const user = me.get('ajax.user');
if (!user) {
console.warn('No user info found, ignore websocket connect.');
return;
}
if (me.get('connected')) {
console.info('Websocket is connected, reconnect.');
me.disconnect();
}
const client = new StompJs.Client({
// brokerURL: 'ws://localhost:15674/ws',
webSocketFactory: function () {
// Note that the URL is different from the WebSocket URL
return new SockJS('/stomp');
},
connectHeaders: {
user: user.id,
// passcode: 'password',
},
debug: function (str) {
console.log(str);
},
reconnectDelay: 5000,
heartbeatIncoming: 4000,
heartbeatOutgoing: 4000,
});
client.onConnect = function(frame) {
// Do something, all subscribes must be done is this callback
// This is needed because this will be executed after a (re)connect
console.info('Websocket connected: ', frame);
me.set('subscription', client.subscribe('/topic/' + user.id, function(msg) {
console.info('On websocket message: ', msg);
$.trigger('WEBSOCKET', [JSON.parse(msg.body)]);
}));
me.set('connected', true);
};
client.onDisconnect = function(frame) {
console.log('On websocket disconnect: ', frame);
me.set('connected', false);
};
client.onStompError = function (frame) {
// Will be invoked in case of error encountered at Broker
// Bad login/passcode typically will cause an error
// Complaint brokers will set `message` header with a brief message. Body may contain details.
// Compliant brokers will terminate the connection after any error
console.log('Broker reported error: ', frame.headers['message']);
console.log('Additional details: ', frame.body);
me.set('connected', false);
};
client.onWebSocketClose = function(event) {
console.log('On websocket close.', event);
};
client.activate();
me.set('client', client);
},
willDestroy() {
const me = this;
me._super(...arguments);
me.disconnect();
},
disconnect() {
const me = this;
if (me.get('connected') && me.get('client')) {
me.get('client').deactivate();
return;
}
console.info('Websocket is not connected, ignore disconnect.');
}
});