如何限制tornado websocket消息大小

2024-10-02 10:30:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我用tornado编写了一个websocket服务器,当收到消息时调用on_message方法。问题是,消息大小不受限制,换句话说,通过从客户端向websocket发送大量数据(消息)来攻击项目,使服务器端内存满。必须有一个选项来限制传入邮件的大小,是吗?如果没有,我该怎么做才能避免这样的错误?

这是我的代码,它只获取长度小于128字节的消息,但似乎不起作用。

class ClientWebSocketConnectionHandler(tornado.websocket.WebSocketHandler):

    def open(self):
        print "Connection is opened"

    def on_message(self, message):
        print message

    def on_close(self):
        print "closed"

handlers = [(r'/', ClientWebSocketConnectionHandler)]
tornado.web.Application.__init__(self, handlers)
TheShieldsWebSocket = MainApplication()
server =tornado.httpserver.HTTPServer(TheShieldsWebSocket,max_body_size=128)
server.listen(8080)

Tags: 方法self服务器消息messageserveronhandlers
2条回答

请看这里的文档:

http://www.tornadoweb.org/en/stable/http1connection.html#tornado.http1connection.HTTP1Connection.set_max_body_size

为便于日后验证,请解释以下链接:

set_max_body_size(max_body_size)[source]

Sets the body size limit for a single request.

Overrides the value from HTTP1ConnectionParameters.

由于4.5版Tornado在单个websocket帧(消息)中接收到超过10兆字节的数据,它将自动关闭连接。所以,你不必担心有人在一条消息中发送大量数据。您可以在source code中看到这一点。在最后第二段的^{}文档中也提到了这一点。在

如果要更改默认的帧限制,可以向Application类传递一个名为websocket_max_message_size的参数,其大小以字节为单位。在

app = tornado.web.Application(
      # your handlers etc,
      websocket_max_message_size=128
)

相关问题 更多 >

    热门问题