1

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 Answer 1

1

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)
3
  • thank you this is working, so the client tries to connect only once to the server now. However I want to display an error message to the client if it cant connect. So I basically need a way to catch the connection error. Aug 15, 2021 at 4:34
  • @DanielResch try this socket.on("connect_error", callback) and socket.on("disconnect", callback) Aug 15, 2021 at 4:38
  • 1
    thank you the on("connect_error") does exactly what I was looking for, you could include that in your answer. I just dont understand what the connect_failed event is for then. Aug 15, 2021 at 4:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.