javascript - How correct recconect to socket via angularjs service? -


i write angularjs app , have problem. app use socket connection data every time. reason write factory(code below).

var service = {}; var ws = new websocket("url"); var timer;  service.onmessage = function(message) { /* 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) { /* code */};  service.connect = function() {         // (re)connect          // reattaching handlers object         ws.onmessage = service.onmessage;         ws.onclose = service.onclose;         ws.onopen = service.onopen;         ws.onerror = service.onerror; } return service; 

and problem have? simplicity lats imagine server down. , socket connection down too. after onclose event start. dont understand how re-connect socket. should check connection every 1 or 5 seconds, example. in code if socket closed, create new socket object , try connect anew. , have? when server up, have many-many objects connect socket. please me. how can fixed this, example, have 1 object(one current connect)?

but dont understand how re-connect socket. should check connection every 1 or 5 seconds

i think not pure angular related question, here general javascript answer (non tested):

  function reconnect(url){    ws = new websocket(url);   }    ws.onclose = function(){    mytimeout = settimeout(function(){reconnect('mywsurl')}, 5000);   }; 

in angular use:

var interval = $interval(your_callback, 5000); 

and cancel timeout:

$interval.cancel(interval); 

i suggest read code of lib, interesting.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -