我用Tornado編寫了一個Tcp服務器。 這裏是代碼:如何在TCP Server中使用Tornado.gen.coroutine?
#! /usr/bin/env python
#coding=utf-8
from tornado.tcpserver import TCPServer
from tornado.ioloop import IOLoop
from 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()
而且我面對一些eorror assert self._read_callback is None, "Already reading"
,我猜eorror是因爲多個命令從插座在同一time.and讀的話,我改變功能send_messages
與tornado.gen.coroutine其中有代碼:
@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()))
但還有一些其他錯誤。代碼在yield self.send_message(b'hello \n')
後似乎停止,並且下面的代碼看起來不會執行。 我應該怎麼做呢?如果您知道任何Tornado tcpserver(不是HTTP!)代碼與tornado.gen.coroutine,請告訴我。我將不勝感激任何鏈接!
非常感謝 – zonzely