问题描述
我在 tornado 中编写了一个 websocket 服务器,并且在接收到消息时调用 on_message
方法.问题是,默认的消息大小是无限的,换句话说,通过从客户端向websocket发送大量数据(消息)来打开项目以进行攻击,这使得服务器端内存已满.必须有一个选项来限制传入消息的大小,是吗?如果没有,我该怎么做才能避免这种错误?
这是我的代码,用于获取仅小于 128 字节长度的消息,但它似乎不起作用.
I have written a websocket server in tornado and on_message
method is called when a message is received. The problem is, the message size is unlimited by defualt, In other word, the project is opened to attack by sending a huge data(Message) from a client to the websocket and it makes the server side memory full. there has to be an option to put a limit on incoming message size, is there? if not, what i have to do to avoid such bug?
Here is my code to get messages only less than 128 byte length, but it doesn't seem to work.
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)
推荐答案
从 4.5 版本开始,如果 Tornado 在单个 websocket 帧(消息)中收到超过 10 MiB 的数据,它将自动关闭连接.因此,您不必担心有人在一条消息中发送大量数据.您可以在源代码.它也在 WebsocketHandler
在倒数第二段.
Since version 4.5 Tornado will close the connection automatically if it receives more than 10 MiB of data in a single websocket frame (message). So, you don't have to worry about someone sending huge data in a single message. You can see this in the source code. It's also mentioned in the docs of WebsocketHandler
in the second-last paragraph.
如果您想更改默认帧限制,您可以向 Application
类传递一个名为 websocket_max_message_size
的参数,其大小以字节为单位.
If you'd like to change the default frame limit you can pass your Application
class an argument called websocket_max_message_size
with the size in bytes.
app = tornado.web.Application(
# your handlers etc,
websocket_max_message_size=128
)
这篇关于如何限制龙卷风 websocket 消息大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!