javascript - socket.io 是如何工作的?

标签 javascript node.js socket.io

我使用的是 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 and connecting.

The transport connection can be closed, closing, open, and opening.

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/

相关文章:

node.js - 如何将图像写入具有缓冲区的服务器?

javascript - express.js 以任意顺序链式路由

node.js - Socket.io:如何正确加入和离开房间

javascript - 使用 mustache 呈现 HTML 标记属性

java - 如何将 Rhino Javascript 1.7 库添加到 Weblogic 10 中的类路径

javascript - 将变量的值更改为可能已经存在的值

java - 存储大量套接字的最佳做法是什么?

javascript - Node.js - 连接到同一个服务器,同一个用户,使用多个 html 文件

javascript - 如何一起使用socket.io和express?

javascript - Node.JS 套接字服务器和同一服务器上的连接速度变慢