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)
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.
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
)