我開始使用Twisted進行異步編程,並且遇到了這個簡單的問題,我不知道如何處理。一個快速分解的問題提供如下:Twisted中的異步操作被鍵盤I/O阻塞
- 服務器1是一個UDP服務器監聽我的主機給定的端口。
- 服務器1公開了用於數據處理的操作的API。
- 服務器2也是在我的主機的不同端口上偵聽的UDP服務器。
- 服務器2正在運行while循環,從用戶獲取I/O以選擇將發送到服務器1的請求。例如,請考慮計算數字階乘的請求。
- 從用戶處獲得輸入後,服務器2向服務器1發出異步呼叫。此呼叫具有關聯的回叫以處理將從服務器1獲取的響應。
- 進行呼叫後,循環達到請再次詢問用戶輸入/輸出的位置。我可以在日誌中看到服務器1處理請求併發送響應,但服務器2中的回調從未執行!一旦我從while循環中斷回執行回調。
我試着在一個單獨的線程中運行I/O代碼,但我無法弄清楚如何使操作非阻塞。有沒有人對我如何解決這個問題有任何建議?
謝謝你的時間!
編輯1.這裏是服務器2正在執行我猜你有扭曲的誤解的代碼(一個與I/O環路發出請求)
# Not including the Twisted code
addr = ("Server 1's IP", "Server 1's Port Number")
# Server class implements the functions to make calls and callbacks that act on responses from Server 1
chordServer = Server(2, "This server's IP", "This Server's port")
server = internet.UDPServer(8468, chordServer.protocol)
server.setServiceParent(application)
def controlLoop(q):
command = None
while 1:
command = input("Enter command: \n 1) join network \n 2) leave network \n 3) store key \n 4) fetch key\n 5) exit\n")
if command == 1:
print ">>> Executing Join Network Comand!"
q.put(command)
elif command == 2:
print ">>> Executing Leave Network Comand!"
q.put(command)
elif command == 3:
continue
elif command == 4:
continue
elif command == 5:
q.put(command)
#time.sleep(1)
def main():
cmd_queue = Queue.Queue()
dj = threading.Thread(target=controlLoop, args=(cmd_queue,))
dj.start()
while 1:
cmd = cmd_queue.get()
if cmd == 5:
break # Only after breaking does the callback associated with the calls below execute
elif cmd == 1:
chordServer.joinNetwork(addr) # Async call to Server 1
elif cmd == 2:
chordServer.leaveNetwork() # Another possible Async call to Server 1
task.deferLater(reactor, 5, main)
如果您發佈代碼,我們可能會提供幫助。 –
有很多,我會嘗試將它抽象成一個簡單的例子@KlausD。 – macalaca
@KlausD。我添加了服務器2正在執行的代碼。我覺得這肯定是一個愚蠢的錯誤,感謝你的幫助。 – macalaca