简体   繁体   English

使用socketio的Websocket可用性

[英]Websocket availability using socketio

I'm trying to detect whether the websocket is running before allowing clients to connect to it. 我正在尝试在允许客户端连接它之前检测websocket是否正在运行。 Consider the following code: 考虑以下代码:

var socket = io.connect('1.1.1.1:1234');
        socket.on('connect',function() {
            console.log('Client has connected to the server');
        });

        socket.on('disconnect',function() {
            console.log("The client has disconnected from the server");
        });

How can I make sure that this block is only called if the server on that IP is actually running and how can I output a message to the users stating that the server is not up? 如何确保仅在该IP上的服务器正在运行时才调用此块,并且如何向用户输出一条消息,指出服务器未启动?

Thank you 谢谢

You would need to fire the io.connect() atleast once (consider this as a ping) to detect if server is up, but you can then handle the failure to connect with the socket.on('connect_failed', function () {}) event handler and show a message to user that the 'server is down'. 您需要至少触发一次io.connect()(将其视为ping),以检测服务器是否启动,但是您可以处理与套接字连接失败的问题。on('connect_failed',function(){ })事件处理程序,并向用户显示“服务器已关闭”的消息。
Have a look at Exposed Events for the client 看看客户的暴露事件

Further, if you would want to reduce the number of times the reconnect is attempted, you can change the socket.io configuration setting for 'reconnect' to false. 此外,如果要减少尝试重新连接的次数,可以将“重新连接”的socket.io配置设置更改为false。
Checkout Socket.io Configuration for more details 查看Socket.io配置以获取更多详细信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM