python 中的异步服务器代码在使用 asyncio.start_server 时将无法工作
async server code in python wont work when using asyncio.start_server
这是异步的 python,但是当我向它发送请求并使用 time.sleep(5) 进行并行测试时它不会工作,但它是顺序的并且请求顺序执行:
def main(*args):
loop = get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 50008,loop=loop)
srv = loop.run_until_complete(coro)
def handle_echo(reader, writer):
data = yield from reader.read(500)
message = data.decode(encoding='utf-8')
nameindex=('name="calculator2"' in message)
if nameindex:
time.sleep(5)
writer.write("Content-Length: 1\r\n\r\n2".encode())
yield from writer.drain()
else:
writer.write("Content-Length: 1\r\n\r\n1".encode())
yield from writer.drain()
print("Close the client socket")
writer.close()
替换:
time.sleep(5)
与:
await asyncio.sleep(5)
这是异步的 python,但是当我向它发送请求并使用 time.sleep(5) 进行并行测试时它不会工作,但它是顺序的并且请求顺序执行:
def main(*args):
loop = get_event_loop()
coro = asyncio.start_server(handle_echo, '127.0.0.1', 50008,loop=loop)
srv = loop.run_until_complete(coro)
def handle_echo(reader, writer):
data = yield from reader.read(500)
message = data.decode(encoding='utf-8')
nameindex=('name="calculator2"' in message)
if nameindex:
time.sleep(5)
writer.write("Content-Length: 1\r\n\r\n2".encode())
yield from writer.drain()
else:
writer.write("Content-Length: 1\r\n\r\n1".encode())
yield from writer.drain()
print("Close the client socket")
writer.close()
替换:
time.sleep(5)
与:
await asyncio.sleep(5)