简体   繁体   中英

Tornado equivalent to Twisted's dataReceived?

Having used Twisted first, I might not be approaching the problem of bidirectional communication the right way with Tornado.

The Twisted way to receive data would be:

class MyProtocol(Protocol):
    def dataReceived(self, data):
        # Figure out if this is a chunk of a previous message
        # or if it's a new message

I'm doing this with Tornado, which seems to work but is somewhat different:

class MyClient(object):
    @coroutine
    def main_loop(self):
        while True:
            message_header = yield Task(self.stream.read_bytes, 8)

            # Read/write from here

The documentation doesn't seem to suggest any "cleaner" approach (or any approach, for that matter), so am I going about this the right way?

The equivalent to Twisted's Protocol in IOStream would be something like stream.read_until_close(callback=self.connectionLost, streaming_callback=self.dataReceived) . But it's more idiomatic to do what you've done in your second example, and use the other read methods ( read_bytes , read_until , etc) to read out what you need in separate chunks. Note that IOStream is not currently very coroutine-friendly (due to the separate close callback), so it's probably best to write code that interfaces directly with IOStream with explicit callbacks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM