Reputation: 298430
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?
Upvotes: 1
Views: 269
Reputation: 22154
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.
Upvotes: 1