python - How to use Tornado.gen.coroutine in TCP Server? -
i write tcp server tornado. here code:
#! /usr/bin/env python #coding=utf-8 tornado.tcpserver import tcpserver tornado.ioloop import ioloop tornado.gen import * class tcpconnection(object): def __init__(self,stream,address): self._stream=stream self._address=address self._stream.set_close_callback(self.on_close) self.send_messages() def send_messages(self): self.send_message(b'hello \n') print("next") self.read_message() self.send_message(b'world \n') self.read_message() def read_message(self): self._stream.read_until(b'\n',self.handle_message) def handle_message(self,data): print(data) def send_message(self,data): self._stream.write(data) def on_close(self): print("the monitored %d has left",self._address) class monitorserver(tcpserver): def handle_stream(self,stream,address): print("new connection",address,stream) conn = tcpconnection(stream,address) if __name__=='__main__': print('server start .....') server=monitorserver() server.listen(20000) ioloop.instance().start() and face eorror assert self._read_callback none, "already reading",i guess eorror because multiple commands read socket @ same time.and change function send_messages tornado.gen.coroutine.here code:
@gen.coroutine def send_messages(self): yield self.send_message(b'hello \n') response1 = yield self.read_message() print(response1) yield self.send_message(b'world \n') print((yield self.read_message())) but there other errors. code seem stop after yield self.send_message(b'hello \n'),and following code seem not execute. how should ? if you're aware of tornado tcpserver (not http!) code tornado.gen.coroutine,please tell me.i appreciate links!
send_messages() calls send_message() , read_message() yield, these methods not coroutines, raise exception.
the reason you're not seeing exception called send_messages() without yielding it, exception has go (the garbage collector should notice , print exception, can take long time). whenever call coroutine, should either use yield wait finish, or ioloop.current().spawn_callback() run coroutine in "background" (this tells tornado not intend yield coroutine, print exception occurs). also, whenever override method should read documentation see whether coroutines allowed (when override tcpserver.handle_stream() can make coroutine, __init__() may not coroutine).
once exception getting logged, next step fix it. can either make send_message() , read_message() coroutines (getting rid of handle_message() callback in process), or can use tornado.gen.task() call coroutine-style code coroutine. recommend using coroutines everywhere.
Comments
Post a Comment