2015-11-13 34 views
0

我開始使用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) 
+0

如果您發佈代碼,我們可能會提供幫助。 –

+1

有很多,我會嘗試將它抽象成一個簡單的例子@KlausD。 – macalaca

+0

@KlausD。我添加了服務器2正在執行的代碼。我覺得這肯定是一個愚蠢的錯誤,感謝你的幫助。 – macalaca

回答

0

。在Twisted中,reactor運行一個處理所有事件的主要命令循環。你自己實現了兩個永不終止的循環。這樣反應器迴路永遠不會再次達到,扭曲不能工作。你需要的是使用延遲對象和回調。但我意識到Twisted是複雜的,涉及到很多與「正常」編程不同的思維方式,這使得這個主題太複雜,無法在這裏處理。也許你應該做手指導師。它一步一步教授您的基本概念:http://twistedmatrix.com/documents/current/core/howto/tutorial/index.html

+0

我對Twisted或一般的異步處理方面絕對不是很有經驗,但我認爲這是一個我完全看不到的簡單問題。有沒有辦法執行異步調用,以阻止執行?再次感謝! – macalaca

+0

阻止執行與異步調用相反。如果你在Twisted中進行阻塞呼叫,它會阻塞整個反應堆。 –