Home > front end >  Python 2.7 Tornado 5.1.1 send WebSocket messages from another thread
Python 2.7 Tornado 5.1.1 send WebSocket messages from another thread

Time:09-17

I have the latest tornado for Python2.7. I am using it as a websocket server. Since it calls itself an "asynchronous networking library" (see below), it is natural to assume that one can send messages asynchronously. How do I actually do that?

 pip show tornado
---
Metadata-Version: 2.0
Name: tornado
Version: 5.1.1
Summary: Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed.
Home-page: http://www.tornadoweb.org/
Author: Facebook
Author-email: [email protected]

This question has been asked for Python 3 already. My question is about Python2.7. The Python3 solution (tornado.ioloop.asyncio_loop.call_soon_threadsafe) does not work in Python2.7:

    tornado.ioloop.asyncio_loop.call_soon_threadsafe(Send, srv, msg)
AttributeError: 'module' object has no attribute 'asyncio_loop'

I also tried the add_callback function because there are comments in other functions that say "use add_callback to transfer control to the IOLoop's thread" which sounds like exactly what I want... but it doesn't seem to do anything (my callback isn't called.)

I also tried simply calling write_message with a mutex lock, or even from the same thread every time, but this doesn't work: tornado occassionally (and only under moderate load) calls the iostream from the main thread ("event loop") and corrupts it by accessing it concurrently without a lock.

What is the function to safely schedule asynchronous events in the Python2.7 version?

CodePudding user response:

I think I found my problem. The tornado.ioloop.IOLoop.instance() needs to be called only once, and the value saved. This same value needs to be used for start() and add_callback().

(But then if the basic IOLoop already enables asynchronous events, then why are people using the asyncio_loop module in newer versions? Something is suspicious about this software package. It seems very complicated.)

  • Related