Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Max reconnect attempts and exponential back-off. #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 25 additions & 1 deletion stompjs/chat/chat.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@
$(function () {
let stompClient;

let maxConnectionAttempts = 10;
let currentTry = 0;

const stompConfig = {
// Typically login, passcode and vhost
// Adjust these for your broker
Expand All @@ -67,11 +70,32 @@

// Subscriptions should be done inside onConnect as those need to reinstated when the broker reconnects
onConnect: function (frame) {
// Reset retryCount on successful connection
currentTry = 0;

// The return object has a method called `unsubscribe`
const subscription = stompClient.subscribe('/topic/chat', function (message) {
const payload = JSON.parse(message.body);
displayIncomingMessage(payload.user, payload.message);
});
},

beforeConnect: function () {
currentTry++;

console.log(`Connection attempt: ${currentTry}`);
if (currentTry > maxConnectionAttempts) {
console.log(`Exceeds max attempts (${maxConnectionAttempts}), will not try to connect now`);

// It is valid to call deactivate from beforeConnect
stompClient.deactivate();
}
},

// Comment out if you do not want exponential back-off
onWebSocketClose: function () {
stompClient.reconnectDelay = 200 * Math.pow(2, currentTry);
console.log(`Exponential back off - next connection attempt in ${stompClient.reconnectDelay}ms`);
}
};

Expand Down Expand Up @@ -120,4 +144,4 @@
})
</script>
</body>
</html>
</html>