socket.io 握手中的 "t=" 查询参数是什么

What is the "t=" query parameter in a socket.io handshake

socketIO 握手看起来像这样:

http://localhost:3000/socket.io/?EIO=3&transport=polling&t=M5eHk0h

t 参数是什么?找不到解释。

这是 engine.io-client. Its value is a Unique ID generated using the npm package yeasttimestampParam

API 文档中的套接字构造函数选项(下面的文档)中引用了这一点。 If no value is given to timestampParam when creating a new instance of a Socket, the parameter name is switched to t and assigned a value from yeast(). You can see this in the source for on Line 223 of lib/transports/polling.js

Socket constructor() Options

  • timestampParam (String): timestamp parameter (t)

为了阐明 engine.io-client 发挥作用的地方,它是 socket.io-client 的依赖项,socket.io 依赖于它。 engine.io 提供 socket.io 构建的实际通信层实现。 engine.io-clientengine.io 的客户端部分。

为什么socket.io使用t

正如 jfriend00 在评论中指出的那样,t 用于缓存清除。缓存破坏是一种防止浏览器提供缓存资源而不是请求资源的技术。

Socket.io 使用查询字符串中的时间戳参数实现缓存破坏。如果您为 timestampParam 分配值 ts,则时间戳的键将为 ts,如果未分配任何值,则默认为 t。通过在每次对服务器进行轮询时为该参数分配一个由 yeast 创建的唯一值,Socket.io 能够始终从服务器检索最新数据并绕过缓存。由于在没有缓存破坏的情况下轮询传输将无法按预期工作,因此默认情况下启用时间戳,必须明确禁用。

据我所知,Socket.io 服务器不会将时间戳参数用于缓存破坏以外的任何其他用途。

更多关于yeast()

yeast() 保证专门用于缓存清除的压缩唯一 ID。 README 为我们提供了有关 yeast() 工作原理的更多详细信息。

Yeast is a unique id generator. It has been primarily designed to generate a unique id which can be used for cache busting. A common practice for this is to use a timestamp, but there are couple of downsides when using timestamps.

  1. The timestamp is already 13 chars long. This might not matter for 1 request but if you make hundreds of them this quickly adds up in bandwidth and processing time.
  2. It's not unique enough. If you generate two stamps right after each other, they would be identical because the timing accuracy is limited to milliseconds.

Yeast solves both of these issues by:

  1. Compressing the generated timestamp using a custom encode() function that returns a string representation of the number.
  2. Seeding the id in case of collision (when the id is identical to the previous one).

To keep the strings unique it will use the . char to separate the generated stamp from the seed.