socket.io - socketio client: How to handle socketio server down -
i've got socketio server/client working together, want start writing events when server offline on page load or during normal run.
i'm including remote socket.io code in header:
<script src="<?=node_host?>/socket.io/socket.io.js"></script> <script> var nodehost = '<?=node_host?>'; </script>
and in client controller have
if(typeof io != 'undefined') this.socket = io.connect(this.settings.server); else this.handledisconnect();
the function have attempt re-connect on , on if a) socket disconnect occurs during normal operation, or b) server down on page load
botcontroller.prototype.handledisconnect = function() { $.getscript(nodehost+"/socket.io/socket.io.js").done(function(script, textstatus) { bot.control.socket = io.connect(bot.control.settings.server); }).fail(function(jqxhr, settings, exception) { settimeout(function() { bot.control.handledisconnect(); }, 5000); }); }
am going correct way?
the main issue have right (which made me create question) code errors on page load when server down because have functions like:
socket.on(...
when socket doesn't yet exist. wrap in function , call when detect global socket object exists on successful reconnection? matter if function contains socket.on... called multiple times (if server goes down more once during operation)?
ok managed come solution seems work using yepnope had using modernizr (it handles cross domain issue me too).
<script src="<?=node_host?>/socket.io/socket.io.js"></script> <script> var nodehost = '<?=node_host?>'; </script>
// attempt connect nodejs server botcontroller.prototype.start = function() { // our nodejs server yet? if(typeof io != 'undefined') { this.socket = io.connect(this.settings.server); this.startsocketevents(); } else { this.handledisconnect(); } } // our connection server has been lost, need keep // trying until have it! botcontroller.prototype.handledisconnect = function(destroysocketobject) { if(destroysocketobject === undefined) destroysocketobject = true; // destroy cached io object before requesting script again if(destroysocketobject) io = undefined; yepnope.injectjs(nodehost+"/socket.io/socket.io.js", function(result) { // did download script ok? if(typeof io != 'undefined') { bot.control.socket = io.connect(bot.control.settings.server); bot.control.startsocketevents(); } else { settimeout(function() { bot.control.handledisconnect(false); }, 5000); } } );
where startsocketevents() function contains of socket.on events
Comments
Post a Comment