Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
580 views
in Technique[技术] by (71.8m points)

javascript - Automatic reconnect with Stomp.js in Node.js application

I'm working with an application that is written in Node.js and Express, and I'm trying to use the Stomp.js client to connect to an ActiveMQ server.

I can get the application to connect to ActiveMQ just fine using Stomp, but I am unable to get the system to automatically reconnect upon connection failure. It seems like the failure function is only called if the connection is initially successful and then later severed, though if ActiveMQ is already down when the Node app starts, I do see the error message that proves the failure function was called.

var Stomp = require('stompjs');
var stompClient = Stomp.overTCP('localhost', 61612);
var stompStatus = false;

var stompSuccessCallback = function (frame) {
    stompStatus = true;
    console.log('STOMP: Connection successful');
};

var stompFailureCallback = function (error) {
    stompStatus = false;
    console.log('STOMP: ' + error);

    setTimeout(stompConnect, 10000);
    console.log('STOMP: Reconecting in 10 seconds');
};

function stompConnect() {
    console.log('STOMP: Attempting connection');
    stompClient.connect('login', 'password', stompSuccessCallback, stompFailureCallback);

}

stompConnect();

Does anybody have any idea what's going on here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The WebSocket that is held by the Stomp.client can only be opened once. If there is a network failure, reconnecting with the same StompClient will not work as the web socket will remain closed.

This can definitely be improved by stomp.js but in the mean time, you can workaround this by recreating a Stomp.client when a failure is detected. Something like:

var stompClient;

var stompFailureCallback = function (error) {
    console.log('STOMP: ' + error);
    setTimeout(stompConnect, 10000);
    console.log('STOMP: Reconecting in 10 seconds');
};

function stompConnect() {
    console.log('STOMP: Attempting connection');
    // recreate the stompClient to use a new WebSocket
    stompClient = Stomp.overTCP('localhost', 61612);
    stompClient.connect('login', 'password', stompSuccessCallback, stompFailureCallback);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...