I am subscribing to a socket using ng2-stomp-service:
this.fooSubscription = this.stomp.subscribe('/topic/foo', (res) => {
console.log('do stuff with res');
});
Sometimes the connection is lost, and I see "Whoops! Connection is lost. Reconnecting..."
At that point, Stomp automatically re-connects, but it never re- subscribes so I can start receiving data again.
How do I re-subscribe after Stomp automatically re-establishes the connection, so I can start receiving data again?
Stomp Service try to reconnect when the onError
method is called.
I resolved your problem overriding the onError
method of the StompService class in my controller:
/**
* Unsuccessfull connection to server
*/
public onError = (error: string ) => {
console.error(`Error: ${error}`);
// Check error and try reconnect
if (error.indexOf('Lost connection') !== -1) {
if(this.config.debug){
console.log('Reconnecting...');
}
this.timer = setTimeout(() => {
this.startConnect();
}, this.config.recTimeout || 5000);
}
}
with the following:
this.stompService.onError = (error: string) => {
console.error(`Error: ${error}`);
// Check error and try reconnect
if (error.indexOf('Lost connection') !== -1) {
console.log('Reconnecting...');
this.timer = setTimeout(() => {
this.stompService.startConnect().then(() => {
// ADD HERE THE SUBSCRIPTIONS
this.socketSubscription = this.stompService.subscribe('/topic/foo', this.response);
}).catch(err => console.error('Connessione al socket non riuscita'));
}, this.stompService.config.recTimeout || 5000);
}
}
adding the subscriptions into the startConnect().then()
.
I'm still open to suggestions here, but for now, I wanted to share the way in which I am currently getting around this problem.
On the stomp object, I noticed there were several properties, including another object called stomp
. In there, I found an object called subscriptions
that has one property for each current subscriptions (named with the string 'sub-' followed by a number, representing the index of the subscriptions... so the first subscription is ' sub-0
'. All those properties get wiped out in the event of a re-connect, resulting in an empty object.
So in my code, all I do is (once per second) check to see if I need to re-subscribe by checking to see if that subscriptions property has any properties.
setInterval(() => {
if (this.stomp.status === 'CONNECTED' && !this.stomp.stomp.subscriptions['sub-0']) {
this.reestablishSubscriptions();
}, 1000);
reestablishSubscriptions() {
this.mySubscription = this.stomp.subscribe('/topic/foo', (res) => {
// do stuff with subscription responses
}
this.myOtherSubscription = this.stomp.subscribe('/topic/foo2', (res) => {
// do stuff with subscription responses
}
}
Yeah, it's ugly... but that's why I'm definitely still open to suggestions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.