应用层WebSocket, since 2022-01-25

2022-01-25  本文已影响0人  Mc杰夫

(2022.01.25 Tues)

websocket协议概述

一些基于浏览器的应用需要与服务器建立双边(duplex)通信,按照传统应用层协议需要建立多个HTTP连接。该协议针对这种情况,提供一种不需要建立多个HTTP连接的通信机制。
The goal of this technology is to provide a mechanism for browser-based applications that need two-way applications between servers that does not need opening multiple HTTP connections.

该协议由开放式握手和基于TCP的基本消息框架组成。
The protocol consists of opening handshaking followed by basic message framing, layered over TCP.

传统应用层协议的问题

按照以往的应用层协议,诸如即时通信和游戏应用会对要求服务器和客户端之间频繁双边通信,这种应用的客户端会频繁建立HTTP连接轮询服务器以获得信息更新,同时服务端也会使用HTTP推送信息。
Historically, creating a web application that need bidirectional communication between a client and server, e.g., instant messaging and game application, has required an abuse of HTTP to poll the server for updates while sending upstream notifications as distinct HTTP calls.
这种应用导致了如下三种问题:

这些问题在客户端服务器端频繁通信的应用中尤其明显,这类应用除了上面提到的instant messaging, gaming application,还包括stock tickers, multiple user application with simultaneous editing多人在线编辑文档,user interfaces exposing server-side services in real time等等。

简单的解决方案是使用单一的TCP连接用于双边通信,也就是WebSocket协议的解决方案。

WebSocket协议

(2022.01.26 Wed)
WebSocket协议分为两部分,a handshake and the data transfer。握手之后,信道畅通,收发两端实现不间断通信。client-server两端都可以向对向发送信息,实现双工通信(duplex)。

握手

握手的URL可通过HTTP方式,也可通过WebSocket独有的协议实现。
握手时,client向server 发送如下信息

GET /chat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Origin: http://example.com
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13

而server向client发送如下信息

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
Sec-WebSocket-Protocol: chat

握手之后,client-server即可实现数据传输。

WebSocket与TCP和HTTP的关系

WS是独立的、基于TCP的协议。WS与HTTP的关系在于WS的握手被HTTP服务器解释为一个Upgrade请求。

默认情况下,WS使用port 80作为WS的常规连接端口,使用port 443作为WS的TLS连接端口, i.e., Transport Layer Security。

下图是HTTP与WebSocket工作流程的对比


HTTPvsWebSocket.png

WebSocket协议实现过程中,可通过HTTP握手,也可使用WebSocket协议握手。如果协议标识符为ws(或加密的wss),则URL为

ws://something.com:80/something/path

Reference和解释

1 https冒号//datatracker点ietf点org/doc/html/rfc6455
2 polling-轮询

上一篇 下一篇

猜你喜欢

热点阅读