根据 RFC 6455 Websocket 标准
第一部分:
.. the server has to prove to the client that it received the
client's WebSocket handshake, so that the server doesn't accept
connections that are not WebSocket connections. This prevents an
attacker from tricking a WebSocket server by sending it carefully
crafted packets using XMLHttpRequest [XMLHttpRequest] or a form
submission.
...
For this header field, the server has to take the value (as present
in the header field, e.g., the base64-encoded [RFC4648] version minus
any leading and trailing whitespace) and concatenate this with the
Globally Unique Identifier (GUID, [RFC4122]) "258EAFA5-E914-47DA-
95CA-C5AB0DC85B11" in string form, which is unlikely to be used by
network endpoints that do not understand the WebSocket Protocol.
第二部分:
The |Sec-WebSocket-Key| header field is used in the WebSocket opening
handshake. It is sent from the client to the server to provide part
of the information used by the server to prove that it received a
valid WebSocket opening handshake. This helps ensure that the server
does not accept connections from non-WebSocket clients (e.g., HTTP
clients) that are being abused to send data to unsuspecting WebSocket
servers.
因此,由于标准中指定了 GUID 的值,因此不知道 Websockets 的服务器不太可能(可能,以非常小的概率)使用它。它不提供任何安全性(安全 websockets - wss:// - 提供),它只是确保服务器理解 websockets 协议。
真的,正如您所提到的,如果您知道 websockets(这是要检查的),您可以通过发送正确的响应来假装是 websocket 服务器。但是,如果您的行为不正确(例如正确地形成帧),它将被视为违反协议。其实你可以写一个不正确的websocket服务器,但是用处不大。
另一个目的是防止客户端意外请求 websockets 升级而不是期望它(例如,通过手动添加相应的标头然后期望其他)。Sec-WebSocket-Key 等相关头信息禁止setRequestHeader
在浏览器中使用方法设置。