我可以在 Python 中通过 tornado websocket 发送 gzip 压缩数据吗?

Can I send gzip compressed data through tornado websocket in Python?

我想将 gzip 压缩数据从 tornado 服务器发送到 javascript 客户端。这是我的代码。

buf = StringIO()
gfile = gzip.GzipFile(mode='wb', fileobj=buf)
try:
    gfile.write( "hello world" )
finally:
    gfile.close()

compressed_data = buf.getvalue()    
self.write_message( compressed_data )

服务器端不提供错误。但是 chrome 产生错误 "Could not decode a text frame as UTF8"。

这里有什么解决方法吗?

使用self.write_message(compressed_data, binary=True)发送二进制消息。您还需要更改应用程序的客户端以解压缩它。

请注意,二进制数据在 javascript 中可能很难处理,因此您可能希望使用 websocket 压缩扩展而不是自己压缩数据(这将使 Tornado 自动压缩数据,并且浏览器会解压)。

要启用此功能,请覆盖 WebSocketHandler 子类中的 get_compression_options()

def get_compression_options(self):
    return {}

空字典使用默认值,或者您可以 return 参数,例如 {'compression_level': 9}。使用此模式时,您只需像往常一样编写消息而不是压缩它。