我是Python 3的新手,正在玩asyncio.因此,我遇到了以下服务器端代码的奇怪行为:
import asyncio
@asyncio.coroutine
def handle_client(reader, writer):
print('Client connected.')
client_connected = True
while client_connected:
print('Waiting for client event.')
line = yield from reader.readline()
if line:
print('Got: {}'.format(line))
if line.decode() == 'echo\n':
print('Sending back echo.')
writer.write(line)
else:
print('Not sending back anything.')
else:
print('Client disconnected.')
client_connected = False
if __name__ == '__main__':
asyncio.async(asyncio.start_server(handle_client, 'localhost', 8888))
asyncio.get_event_loop().run_forever()
Run Code Online (Sandbox Code Playgroud)
当我运行这个客户端代码时(编辑:客户端代码手动输入到IPython会话中,服务器肯定有时间在关闭套接字之前写入)...
import socket
client = socket.create_connection(('localhost', 8888))
client.sendall('echo\n'.encode())
client.close()
Run Code Online (Sandbox Code Playgroud)
...我从服务器收到错误回溯:
C:\Users\Gnar\Anaconda3\python.exe C:/Users/Gnar/Code/echo.py
Client connected.
Waiting for client event.
Got: b'echo\n'
Sending back echo.
Waiting for …Run Code Online (Sandbox Code Playgroud)