11

Websocket 的设计使其服务器可以与 HTTP 服务器共享端口,方法是让其握手成为有效的 HTTP 升级请求。

我对这种设计理念持怀疑态度。无论如何,WebSocket 协议都是一个独立的基于 TCP 的协议。

为什么我们需要这个 HTTP 握手(升级请求)和协议切换。相反,为什么我们不能直接(独立地)遵循类似 websocket 的协议?

4

1 回答 1

18

引用IETF 6455 WebSocket 规范

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 协议旨在允许对现有基础架构进行调整和扩展,而无需从头开始重新创建所有内容以支持专用端口上的新协议。

同样重要的是要注意,即使 WebSocket 协议要摆脱与 HTTP 兼容的握手,它仍然需要几乎相同复杂性的握手来支持现代 Web 的安全要求,以便浏览器和服务器可以相互验证并支持安全的 CORS(跨域请求共享)。甚至“原始”Flash 套接字在创建实际套接字之前通过安全策略请求与服务器握手。

于 2013-10-24T15:15:23.500 回答