Reputation: 6050
I've got a socketio server/client working well together, however I want to start writing events for when the server is offline on page load or during normal run.
I'm including the remote socket.io code in my header:
<script src="<?=NODE_HOST?>/socket.io/socket.io.js"></script>
<script>
var nodeHost = '<?=NODE_HOST?>';
</script>
And in my client controller I have
if(typeof io != 'undefined') this.socket = io.connect(this.settings.server); else this.handleDisconnect();
The function I have to attempt to re-connect over and over if a) A socket disconnect occurs during normal operation, or b) the server is 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 I going about this the correct way?
The main issue I have right now (which made me create this question) is my code errors on page load when the server is down because I have functions like:
socket.on(...
When socket doesn't yet exist. I could wrap those in a function and call it when I detect the global socket object exists on successful reconnection? Would it matter if that function that contains socket.on... is called multiple times (if the server goes down more than once during operation)?
Upvotes: 4
Views: 1028
Reputation: 6050
OK I managed to come up with this solution that seems to work well using yepnope which I already had using Modernizr (it handles the cross domain issue for me too).
<script src="<?=NODE_HOST?>/socket.io/socket.io.js"></script>
<script>
var nodeHost = '<?=NODE_HOST?>';
</script>
// Attempt to connect to nodejs server botController.prototype.start = function() { // Is our nodejs server up yet? if(typeof io != 'undefined') { this.socket = io.connect(this.settings.server); this.startSocketEvents(); } else { this.handleDisconnect(); } } // Our connection to the server has been lost, we need to keep // trying to get it back until we have it! botController.prototype.handleDisconnect = function(destroySocketObject) { if(destroySocketObject === undefined) destroySocketObject = true; // Destroy any cached io object before requesting the script again if(destroySocketObject) io = undefined; yepnope.injectJs(nodeHost+"/socket.io/socket.io.js", function(result) { // Did it actually download the 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 all of my socket.on events
Upvotes: 0