2011-06-01 56 views
6

我試圖編寫一個程序,讓客戶端連接到它,同時服務器仍然能夠向所有客戶端發送命令。我正在使用「Twisted」解決方案。我怎麼去解決這個問題?這裏是我到目前爲止的代碼(我的理解是扭曲已經使用非阻塞套接字):在Python中監聽連接時接收命令行輸入

import threading 
print 'threading.' 

def dock(): 
    try: 
     from twisted.internet.protocol import Factory, Protocol 
     from twisted.internet import reactor 
     import currentTime 
     print '[*]Imports succesful.' 
    except: 
     print '[/]Imports failed.' 

    #Define the class for the protocol 
    class Master(Protocol): 
     command = raw_input('> ') 
     def connectionMade(self): 
      print 'Slave connected.' 
      print currentTime.getTime() #Print current time 
      #self.transport.write("Hello") 

     def connectionLost(self, reason): 
      print 'Lost.' 
    #Assemble it in a "factory" 

    class MasterFactory(Factory): 
     protocol = Master 


    reactor.listenTCP(8800, MasterFactory()) 

    #Run it all 
    reactor.run() 

def commandline(): 
    raw_input('>') 

threading.Thread(target=dock()).start() 
threading.Thread(target=commandline()).start() 

回答

6

既然你已經使用了雙絞線,你也應該使用它的主機部分,而不是使用raw_input在一個線程中。

Twisted的事件循環可以監視任何文件描述符以進行更改(包括標準輸入),因此您可以在輸入的新行上獲得基於事件的回調 - 它可以異步工作,無需線程。

我找到了這個example of a interactive console in a twisted application,也許你可以使用它。

+0

鏈接已死,請您提供一個工作的? – alex 2013-09-24 18:15:58

+0

@alex http://luoqq.blogspot.com.br/2012/01/song-for-lovers-twisted-interactive.html – nosklo 2013-10-17 11:27:05

+0

'.com.br'對我來說有不可讀的代碼示例。但是[www.oluyede.org/blog/2008/08/31/twisted-interactive-console]網站檔案(http://web.archive.org/web/20091227070520/http://www.oluyede.org/博客/ 2008/08/31/twisted-interactive-console)的作品 – jfs 2013-12-16 07:55:20