在 Socket.io 客户端获取连接状态 [英] Get connection status on Socket.io client

查看:86
本文介绍了在 Socket.io 客户端获取连接状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Socket.io,我想知道客户端连接到服务器的状态.

I'm using Socket.io, and I'd like to know the status of connection to the server from the client-side.

像这样:

socket.status // return true if connected, false otherwise

如果连接断开或由于任何原因断开连接,我需要此信息向用户提供视觉反馈.

I need this information to give a visual feedback to the user if the connection has dropped or it has disconnected for any reason.

推荐答案

您可以检查 socket.connected 属性:

var socket = io.connect();
console.log('check 1', socket.connected);
socket.on('connect', function() {
  console.log('check 2', socket.connected);
});

它是动态更新的,如果连接丢失,它将被设置为 false 直到客户端再次连接.使用 setInterval 或类似的东西很容易检查.

It's updated dynamically, if the connection is lost it'll be set to false until the client picks up the connection again. So easy to check for with setInterval or something like that.

另一种解决方案是捕获 disconnect 事件并自行跟踪状态.

Another solution would be to catch disconnect events and track the status yourself.

这篇关于在 Socket.io 客户端获取连接状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆