Why websocket needs an opening handshake using HTT

2020-05-19 07:52发布

问题:

Websocket is designed in such a way that its servers can share a port with HTTP servers, by having its handshake be a valid HTTP Upgrade request.

I have a doubt in this design philosophy. Any ways the WebSocket Protocol is an independent TCP-based protocol.

Why would we need this HTTP handshake(upgrade request) and a protocol switching. Instead why can't we directly(& independently) follow a websocket like protocol?

回答1:

To quote from the IETF 6455 WebSocket spec:

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.

In other words, there is a vast infrastructure for HTTP and HTTPS that already exists (proxies, firewalls, caches, and other intermediaries). In order to increase the chances of being adopted widely, the WebSocket protocol was designed to allow adjustments and extensions to the existing infrastructure without having to recreate everything from scratch to support a new protocol on a dedicate port.

It's also important to note that even if WebSocket protocol were to get rid of the HTTP compatible handshake, it would still need a handshake of almost equivalent complexity to support security requirements of the modern web so the browser and server can validate each other and to support CORS (cross-origin request sharing) securely. Even "raw" Flash sockets do a handshake with the server via the security policy request prior to creating the actual socket.