2017-03-07 110 views
0

這是異步python,但在向它發送請求並使用time.sleep(5)進行並行測試時不起作用,但它是順序並且執行了請求順序:python中的異步服務器代碼在使用asyncio.start_server時不會工作

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() 
+0

@udi這是我的新代碼 –

+1

別在協程中使用'time.sleep',而是使用[asyncio.sleep](https://docs.python.org/3/library/asyncio-task.html#asyncio.sleep)。 – Vincent

+0

@uid好的,我會測試它並通知你。 Tnx –

回答

1

取代:

time.sleep(5) 

有:

await asyncio.sleep(5) 
+0

Thanks.I使用這段代碼做了它,它的工作原理:從asyncio.sleep(5) –

+0

等待的收益是在python 3.5-我使用Python 3.4爲我的項目,我做了像以前的評論 –

相關問題