1
我很難理解asyncio的整個概念。現在,我嘗試使用Socket模塊和asyncio同時使用UDP聊天作爲服務器和客戶端。在兩個asyncio協程中,我運行循環(一個用於服務器,一個用於客戶端)。但該計劃只能作爲客戶。在網絡上發送數據但沒有收到。我想這個案例中有更好的asyncio解決方案,但在繼續他們之前,我想了解爲什麼沒有特定的代碼工作。你有什麼線索嗎?UDP server_client。在asyncio協程中使用Socket對象沒有併發性
# PYTHON 3.4
import asyncio
import socket
PORT = 50001
MAX_BYTES = 8400
LOCAL_IP = ''
REMOTE_IP = '192.168.1.31'
serverSock= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serverSock.bind(('', PORT))
@asyncio.coroutine
def server():
while True:
data, address = serverSock.recvfrom(MAX_BYTES)
print('New data: {}'.format(data.decode('utf8')))
@asyncio.coroutine
def client():
while True:
toSend = input('Enter to send: ')
serverSock.sendto(toSend.encode(),(REMOTE_IP, PORT))
tasks = [server(), client()]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
我在想象while循環會阻塞事件循環,無論哪個任務是先安排的。 – dm03514
是的,但爲什麼它阻止?無論是在協同程序中的任何東西都應該與其他協同運行。這就是爲什麼我使用asyncio .. – saavedra29
它不以任何方式屈服,我從來沒有使用asyncio,但它需要一些方式來產生事件循環時什麼都沒有發生,像'data,address = yield從serverSock.recvfrom( MAX_BYTES)' – dm03514