节点JS - 你怎么能知道一个套接字已打开与Einaros WS插座模块? [英] Node JS - How Can You Tell If A Socket Is Already Open With The Einaros WS Socket Module?

查看:92
本文介绍了节点JS - 你怎么能知道一个套接字已打开与Einaros WS插座模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前使用einarosWS的NodeJS模块创建的WebSocket客户端。
当初始化客户端的Socket,我用的是开放的事件,以确定当连接是开放的,但一旦它是开放的,我怎么会是能够检查它是否仍然是开放的?

I'm currently using einaros' NodeJS WS module to create a websocket client. When initializing the socket client, I use the 'open' event to determine when the connection is open, but once it's open, how would I be able to check if it's still open?

有没有了的WebSocket对象上的属性,我可以用它来快速检查插座的状态?

Is there a property on the 'WebSocket' object that I can use to quickly check the status of the socket?

时 - 的 websocketInstance.readyState 的 - 充足

Is - websocketInstance.readyState - adequate?

推荐答案

socket.readyState 会告诉你什么插座认为它的状态。有没有其他的,更准确的属性,您可以用比 socket.readyState 咨询。

socket.readyState will tell you what the socket thinks its state is. There is no other, more accurate property that you can consult than socket.readyState.

如果你想知道什么是当套接字已连接完成,现在认为是开放的,那么你就可以报名参加打开事件的事件处理。这会告诉你,当它已经完成连接。

If what you want to know is when the socket has finished connecting and is now considered open, then you can register an event handler for the open event. This will tell you when it has finished connecting.

如果你想有一个实时的通知时,插座关闭或遇到错误时,您可以使用事件侦听器错误关闭事件。在关闭事件只是意味着插座关闭和 socket.readyState 值现在改为关闭。

If you want a real-time notification when the socket closes or experiences an error, you can use an event listener for the error or close events. The close event just means that socket is closing and the socket.readyState value is now changing to closed.

一个更保证达到最新的检查插座的方法是首先检查 socket.readyState ,如果写着插座是开放的,那么你可以发送测试数据包到另一端,只有当你得到一个响应从测试数据包发送回你会真正知道插座是否正常工作。

A more guaranteed to be up-to-date method of checking the socket is to first check socket.readyState and, if that says the socket is open, then you can send a test packet to the other end and only when you get a response back from the test packet will you truly know that socket is operational.

socket.io 库(基于WebSockets的顶部)正是这样做的,定期发送保活数据包并监听响应。如果这样下去,一段时间没有响应,那么它会关闭现有的套接字,并尝试重新建立新的连接(盘算事先连接在某种程度上丢失)。通过这种方式,在 socket.io 库甚至可以存活重启服务器或客户端的互联网连接暂时下降,因为它会看到连接丢失,然后重新透明建立在其位置的新连接。

The socket.io library (built on top of webSockets) does exactly this, sending regular keep-alive packets and listening for responses. If it goes some period of time with no response, then it will close the existing socket and attempt to re-establish a new connection (figuring the prior connection was lost somehow). In this way, the socket.io library can even survive a server reboot or a temporary drop in client internet connectivity as it will see that the connection was lost and then transparently re-establish a new connection in its place.

这篇关于节点JS - 你怎么能知道一个套接字已打开与Einaros WS插座模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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