在Python中侦听连接时接收命令行输入

Dar*_*r56 6 python sockets client twisted

我正在尝试编写一个程序,让客户端连接到它,而服务器仍然能够向所有客户端发送命令.我正在使用"Twisted"解决方案.我怎么能这样做?这是我到目前为止的代码(我知道Twisted已经使用了非阻塞套接字):

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()
Run Code Online (Sandbox Code Playgroud)

nos*_*klo 6

既然你已经使用了twisted,你也应该将它用于控制台部分,而不是raw_input在线程中使用.

Twisted的事件循环可以监控的变化,包括标准输入任何文件描述符,这样你就可以进入一个新的生产线得到基于事件的回调 - 它以异步方式工作,而不需要线程.

在扭曲的应用程序中找到了这个交互式控制台的例子,也许你可以使用它.