Websocket 的设计方式使其服务器可以与 HTTP 服务器共享端口,方法是让其握手成为有效的 HTTP 升级请求。
我对这个设计理念有疑问。 WebSocket 协议(protocol)在任何方面都是一个独立的基于 TCP 的协议(protocol)。
为什么我们需要这种 HTTP 握手(升级请求)和协议(protocol)切换。相反,为什么我们不能直接(和独立地)遵循类似 websocket 的协议(protocol)?
最佳答案
The WebSocket Protocol attempts to address the goals of existing
bidirectional HTTP technologies in the context of the existing HTTP
infrastructure; as such, it is designed to work over HTTP ports 80
and 443 as well as to support HTTP proxies and intermediaries, even
if this implies some complexity specific to the current environment.
However, the design does not limit WebSocket to HTTP, and future
implementations could use a simpler handshake over a dedicated port
without reinventing the entire protocol.
换句话说,已经存在一个庞大的 HTTP 和 HTTPS 基础设施(代理、防火墙、缓存和其他中介)。为了增加被广泛采用的机会,WebSocket 协议(protocol)旨在允许对现有基础架构进行调整和扩展,而无需从头开始重新创建所有内容以在专用端口上支持新协议(protocol)。
同样重要的是要注意,即使 WebSocket 协议(protocol)摆脱了 HTTP 兼容握手,它仍然需要一个几乎相同复杂度的握手来支持现代网络的安全要求,以便浏览器和服务器可以相互验证并安全地支持 CORS(跨源请求共享)。即使是“原始”Flash 套接字也会在创建实际套接字之前通过安全策略请求与服务器握手。
关于http - 为什么 websocket 需要使用 HTTP 打开握手?为什么它不能是一个独立的协议(protocol)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19568432/