首先使用Twisted,我可能不会以正确的方式与Tornado接近双向通信的问题。
接收数据的Twisted方式是:
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
我正在与Tornado一起做这件事,这似乎有效但有些不同:
class MyClient(object):
@coroutine
def main_loop(self):
while True:
message_header = yield Task(self.stream.read_bytes, 8)
# Read/write from here
文档似乎没有暗示任何“更清洁”的方法(或者任何方法),所以我是否正确地采用了这种方式?
答案 0 :(得分:1)
Protocol
中与Twisted IOStream
相当的内容类似于stream.read_until_close(callback=self.connectionLost, streaming_callback=self.dataReceived)
。但是,在第二个示例中执行您所做的事情更加惯用,并使用其他读取方法(read_bytes
,read_until
等)以单独的块读出您需要的内容。请注意,IOStream
目前不是非常友好的(由于单独的关闭回调),因此最好编写直接与IOStream
接口的代码并使用显式回调。