我使用的是 socket.io,它的设置速度很快(感谢他们使用页面上的示例),但我想了解更多关于幕后工作的具体情况以及使它工作的技术。
socket.io 的确切机制是什么?
它是在端口 80 上还是单独的端口上?
它真的保持打开状态还是那部分是模拟的?
有没有办法分析每个套接字事件? (有点像使用 fiddler 来查看 ajax 调用中发生的情况)
最佳答案
对于调试,您可能想尝试 Theseus .
这里是 socket.io SPEC 的简短概述:
Socket.IO aims to bring a WebSocket-like API to many browsers and devices, with some specific features to help with the creation of real-world realtime applications and games.
- Multiple transport support (old user agents, mobile browsers, etc).
- Multiple sockets under the same connection (namespaces).
- Disconnection detection through heartbeats.
- Optional acknoledgments.
- Reconnection support with buffering (ideal for mobile devices or bad networks)
- Lightweight protocol that sits on top of HTTP.
Anatomy of a Socket.IO socket
A Socket.IO client first decides on a transport to utilize to connect.
The state of the Socket.IO socket can be
disconnected
,disconnecting
,connected
andconnecting
.The transport connection can be
closed
,closing
,open
, andopening
.A simple HTTP handshake takes place at the beginning of a Socket.IO connection. The handshake, if successful, results in the client receiving:
- A session id that will be given for the transport to open connections.
- A number of seconds within which a heartbeat is expected (
heartbeat timeout
)- A number of seconds after the transport connection is closed when the socket is considered disconnected if the transport connection is not reopened (
close timeout
).At this point the socket is considered connected, and the transport is signaled to open the connection.
If the transport connection is closed, both ends are to buffer messages and then frame them appropriately for them to be sent as a batch when the connection resumes.
If the connection is not resumed within the negotiated timeout the socket is considered disconnected. At this point the client might decide to reconnect the socket, which implies a new handshake.
如果您需要更多详细信息,可以阅读规范的其余部分 here
关于javascript - socket.io 是如何工作的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16719282/