I have been doing some nodeJS testing with socket.io and have noticed when i don't run the nodeJS my client errors.
When nodeJS is not running I get this error in my client console.log:
Failed to load resource socket.io/socket.io.js
My client code is like this:
<script src = "socket.io/socket.io.js" > < /script>
<script>
window.onload = function(){
if(typeof io != 'undefined'){
socketio = io.connect("[hidden]:[hidden]");
socketio.on('error', function(err) {
if(err === 'handshake error') {
console.log('handshake error', err);
} else {
console.log('io error', err);
}
});
} else {
console.log('IO not started?');
}
}
</scirpt>
So i'm wondering - whats the best way to preiodically check when nodeJS has started up ?
you can send a request to your nodejs server,if server return 500. nodejs is stopping now.
<script>
var socket = io.connect();
socket.on('connect', function(){
console.log('connected');
//do Something...
})
</script>
if you want to check socket.io.js whether it has finished loading, you can try to use Require.js http://requirejs.org/
Not an elegant solution, but this should solve your problem -
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function(){
var connected = 0;
var socket;
var timer = setInterval(function(){
loadScript();
},1000);
function loadScript() {
$.getScript("http://<ip>:<port>/socket.io/socket.io.js")
.done(function( script, textStatus ) {
//console.log( textStatus );
if(!connected) {
socket = io.connect('http://<ip>:<port>');
connected = 1;
clearInterval(timer);
}
});
}
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.