如果无法在 node.js 和 socket.io 中建立与服务器的连接,如何关闭套接字?

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

目前我在 node.js 中使用以下代码和 socket.io 连接到我的服务器,它工作正常。但是如果我的 node.js 服务器不是 运行,客户端会尝试一次又一次地连接到它 - 但如果服务器是,我想停止它并关闭客户端的套接字不能达到。我试过使用 connect_failed,但不幸的是,这从未被调用过。如何做到这一点?

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); 
    }); 


}

为套接字 io 客户端尝试 autoConnectreconnection 选项

{ autoConnect: false, reconnection: false}

编辑:

并且您可以侦听 connect_error 事件以捕获连接错误

socket.on("connect_error", callback)