how to close socket if connection to server cant be established in node.js and socket.io?

Viewed 98

currently I am using the following code in node.js with socket.io to connect to my server, which is working fine. But if my node.js server is not running, the client is trying to connect to it again and again in intervals - but I would like to stop it and close the socket on the client side if the server is not reachable. I have tried using connect_failed, but unfortunately this is never being called. how can this be done?

function findOpponent(gamemode)
{

    console.log('Registering myself on nodejs Server and waiting for 2nd player'); 


    socket = io.connect("http://gladiator.localhost:3000" , {
        'query': '&uuid='+uuid+'&authkey='+auth_key+'&gamemode='+gamemode
    });


    socket.on('connect_failed', function() {
        // --> this is never being called
        console.log("Sorry, there seems to be an issue with the connection!");
    });


    socket.on('user join',function(msg){
        alert('USER JOINED'); 
    }); 

    socket.on('user leave',function(msg){
        console.log(msg); 
        alert('USER LEFT'); 
    }); 


    socket.on('message',function(msg){
        alert(msg); 
    }); 


    socket.on('gamestart',function(data){
        console.log('gamestart'); 
        alert(data.msg); 
    }); 


}
1 Answers

try autoConnect and reconnection options for socket io client

{ autoConnect: false, reconnection: false}

EDIT:

and you can listen on connect_error event for catch connection error

socket.on("connect_error", callback)
Related