I have encountered an issue while writing an AngularJS app. My application relies on a socket connection to retrieve data consistently, so I created a factory as shown below:
var Service = {};
var ws = new WebSocket("url");
var timer;
Service.onMessage = function(message) { /* some code */ };
Service.onClose = function() {
timer = $interval(function () {
ws = new WebSocket("url");
Service.connect();
}, 1000);
};
Service.onOpen = function() {
console.log("open");
if (timer) $interval.cancel(timer);
};
Service.onError = function(error) { /* some code */ };
Service.connect = function() {
// (Re)connect
// Reattaching handlers to object
ws.onmessage = Service.onMessage;
ws.onclose = Service.onClose;
ws.onopen = Service.onOpen;
ws.onerror = Service.onError;
}
return Service;
The problem arises when the server is down and the socket connection is lost. The onClose event triggers but I am unsure how to reconnect with the socket properly. I want to periodically check the connection status, maybe every 1 or 5 seconds. In my current implementation, I create a new socket object each time the connection is lost, resulting in multiple connections when the server comes back online. How can I modify my code to maintain only one active connection? Any suggestions would be greatly appreciated.