Making Tornado websocket handler thread safe

二次信任 提交于 2019-12-11 01:05:27

问题


I am randomly getting error 1006 ( (I failed the WebSocket connection by dropping the TCP connection) when trying to write messages from threads using Tornado's websocket server handler.

I created N threads and passed my ws_handler to them. But when I start using

self.ws_handler.write_message(jsondata)

for a large number of threads, I keep getting the same error.

From what I understand, 1006 is TCP connection dropped when a 'heartbeat' communication is skipped between websockets. I am guessing this is because of threads running in parallel and trying to send messages. I tested it using 2-3 threads and it works fine but for large number it doesn't.

I wonder if there's any method to achieve message sending within threads.( meaning lock being handled internally by ws_handler and sending accordingly).

One solution I am thinking of is to push jsondata into a queue and have another single thread push the messages, but I fear that would create a bottleneck.

My client is AutobahnPython.


回答1:


Tornado is based on a single-threaded event loop; all interactions with Tornado objects must be on the event loop's thread. Use IOLoop.current().add_callback() from another thread when you need to transfer control back to the event loop.

See also http://www.tornadoweb.org/en/stable/web.html#thread-safety-notes



来源:https://stackoverflow.com/questions/20854421/making-tornado-websocket-handler-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!