websocket是否可以支持gzip压缩?

问题描述:

成功握手WebSocket之后,我们可以使用gzip压缩吗?websocket是否可以支持gzip压缩?

这里是我的测试:

  1. 我使用高速公路的lib建立一个服务器,然后respon客户为:
    HTTP/1.1 101 Switching Protocols content-encoding: gzip Connection: Upgrade Server: AutobahnPython/?.?.? Upgrade: WebSocket Sec-WebSocket-Accept: RIR8KmljoV8Cv9mdiLY7GM2nYMc=
  2. 然后我的服务器使用gzip压缩
  3. 和Chrome浏览器了结果,但它告诉我“无法将文本帧解码为UTF-8”
+0

AutobahnPython(当前)不支持每帧压缩扩展。在任何情况下,支持的信号通过WebSocket特定的HTTP标头完成,而不是“内容编码”。 – oberstet 2012-07-25 12:00:58

+0

感谢提醒。任何方式,有一个简单的方法来支持gzip压缩作为http方法使用websocket? – littlesun 2012-07-25 12:28:09

+0

不需要。对于在WebSocket上使用压缩,需要实现扩展,这需要“深入浅出”的重要代码。 – oberstet 2012-07-25 16:15:23

有一个compression extension be由IETF Websocket(HyBi)工作组提供worked on。我会建议您在他们的邮件列表中查找最新的信息。我也推荐检查this question


更新2017年:现在的扩展已经有一段时间了,在这里看到:https://tools.ietf.org/html/rfc7692

+0

你能告诉我如何使用?我在RFC 6455中查了一下,但我不知道如何使用...... – littlesun 2012-07-25 10:06:30

+0

感谢Dreen,那太棒了。我将研究压缩扩展。还有其他朋友正在学习吗? – littlesun 2012-07-25 13:20:42

+0

@littlesun:据我所知,这个扩展还没有提供,因为它仍然在进行中(主要证据是他们只是将其从“每帧”改为“每个消息”设备) 。 Javascript本身并不真正支持任何形式的压缩/解压缩。恐怕现在唯一的解决方案是等待IETF的人们完成规范,并让浏览器供应商实施它......它不应该很长,恕我直言,它可能会在几个月内发生。 – Dreen 2012-07-25 14:52:12

的WebSocket压缩某些浏览器默认启用(在Chrome浏览器编写例如时间,但不在Firefox中)。客户端必须包含'Sec-WebSocket-Extensions:permessage-deflate'标题。如果服务器使用相同的扩展名进行响应,则WebSocket通信将按帧进行压缩。据我所知,没有浏览器API来启用/禁用扩展。

的话题一篇好文章是:https://www.igvita.com/2013/11/27/configuring-and-optimizing-websocket-compression/

是的,它可以。 Chrome 19+ supports it.

"https://github.com/crossbario/autobahn-python/blob/master/examples/twisted/websocket/echo_compressed/server_advanced.py" 

from twisted.internet import reactor 
from twisted.web.server import Site 
from twisted.web.static import File 

from autobahn.twisted.websocket import WebSocketServerFactory, \ 
    listenWS 

from autobahn.websocket.compress import * 

def accept(offers): 
    for offer in offers: 
     return PerMessageDeflateOfferAccept(offer) 

debug = True 
factory = WebSocketServerFactory(u"ws://127.0.0.1:9000", debug=debug, debugCodePaths=debug) 
factory.setProtocolOptions(perMessageCompressionAccept=accept) 

listenWS(factory) 

webdir = File(".") 
web = Site(webdir) 
reactor.listenTCP(8080, web) 

reactor.run() 

更多信息:how PerMessageDeflateOffer is used in Autobahn examples