Could websocket support gzip compression?

2019-01-18 19:14发布

问题:

After the success handshake of WebSocket, could we used gzip compression?

Here are my tests:

  1. I use autobahn lib to build a server, then respon to client as:
    HTTP/1.1 101 Switching Protocols content-encoding: gzip Connection: Upgrade Server: AutobahnPython/?.?.? Upgrade: WebSocket Sec-WebSocket-Accept: RIR8KmljoV8Cv9mdiLY7GM2nYMc=
  2. then my server uses gzip compression
  3. and the chrome browser got the result, but it told me that "could not decode a text frame as UTF-8"

回答1:

WebSocket compression is enabled in some browsers by default (at the time of writing for example in Chrome, but not in Firefox). The client has to include the 'Sec-WebSocket-Extensions: permessage-deflate' header for this. If the server responds with the same extension, the WebSocket communication is compressed on a frame basis. As far as I know, there is no browser API to enable/disable extensions.

A good article about the topic is: https://www.igvita.com/2013/11/27/configuring-and-optimizing-websocket-compression/



回答2:

There is a compression extension being worked on by the IETF Websocket (HyBi) working group. I would suggest following their mailing list for up-to-date information. I also recommend checking out this question.


Update 2017: The extension has now been available for some time, see here: https://tools.ietf.org/html/rfc7692



回答3:

Yes it could. 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()

More info: how PerMessageDeflateOffer is used in Autobahn examples.