我有以下服务器代码:
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream, StreamClosedError
from tornado.tcpclient import TCPClient
from tornado.tcpserver import TCPServer
from tornado.platform.asyncio import to_tornado_future, to_asyncio_future
class MyServer(TCPServer):
async def handle_stream(self, stream, address):
try:
while True:
encoded="***".encode()
msg= await stream.read_until(encoded)
print(msg)
except StreamClosedError:
print("connection error")
server = MyServer()
server.listen(10000)
IOLoop.current().start()
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream, StreamClosedError
from tornado.tcpclient import TCPClient
from tornado.platform.asyncio import to_tornado_future, to_asyncio_future
tcp_client = TCPClient()
async def client():
while True:
try:
stream = await tcp_client.connect('localhost', 10000)
# Set TCP_NODELAY / disable Nagle's Algorithm.
stream.set_nodelay(True)
while True:
msg ="hello ***"
await stream.write(msg.encode())
await gen.sleep(5)
except StreamClosedError as exc:
print("error connecting")
loop = IOLoop.current()
loop.spawn_callback(client)
loop.start()
我在服务器端不断收到警告,handle_stream从未被等待:
/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tornado-4.4.2-py3.5-macosx-10.6-intel.egg/tornado/netutil.py:272: RuntimeWarning: coroutine 'MyServer.handle_stream' was never awaited
callback(connection, address)
ERROR:tornado.application:Error in connection callback
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tornado-4.4.2-py3.5-macosx-10.6-intel.egg/tornado/tcpserver.py", line 276, in _handle_connection
self.io_loop.add_future(future, lambda f: f.result())
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/tornado-4.4.2-py3.5-macosx-10.6-intel.egg/tornado/ioloop.py", line 593, in add_future
有人能告诉我我做错了什么,以及如何使用异步和等待来实现这一点吗。
这与杰西善意回答的以下问题有关:
Tornado TCP Server / Client process communication
我试着让他的代码使用异步和等待,但是有同样的问题…如果我改变上面的代码使用yield和协程,它会工作。。。