Websocket 中的 sub-protocol 和 extensions 的关系

时间:2024-03-29 16:12:09

当时看 RFC6455 的时候,对 Sub-protocol 和 Extensions 感到很困惑,子协议是客户端提交几个子协议的列表(带优先序),交给服务器判断要使用那一个协议,然后再由服务器返回一个选中的子协议给客户端。而扩展则是客户端提交一个扩展列表(带顺序和参数)给服务器,然后由服务器决定要使用那些扩展,然后返回一个扩展列表给客户端(带顺序和参数)。

在文档中对这两个部分的描述并不是很清晰,并没有明确的举例说明这两个部分该如何使用,在搜索相关的资料的时候,在mozila的开发者网站上发现了这篇文章:

Writing WebSocket servers - Web APIs | MDN

其中提到:

Think of an extension as compressing a file before emailing it to someone. Whatever you do, you're sending the same data in different forms. The recipient will eventually be able to get the same data as your local copy, but it is sent differently. That's what an extension does. WebSockets defines a protocol and a simple way to send data, but an extension such as compression could allow sending the same data but in a shorter format.

Think of a subprotocol as a custom XML schema or doctype declaration. You're still using XML and its syntax, but you're additionally restricted by a structure you agreed on. WebSocket subprotocols are just like that. They do not introduce anything fancy, they just establish structure. Like a doctype or schema, both parties must agree on the subprotocol; unlike a doctype or schema, the subprotocol is implemented on the server and cannot be externally referred to by the client.

里面用压缩软件来举例说明了扩展的作用,同时用XML语法来类比子协议。同时强调了,子协议是服务器实现的,客户端不能从外部引用。如果从这个角度来看,子协议应该就是对 payload 的内部处理方式(代码级别),而扩展则是对 payload 的外部处理方式(程序级别)。

而处理的顺序则已经标明:

payload -> extensions (in order) -> sub-protocol -> webscoket

以上。