我正在尝试编写一个程序,让客户端连接到它,而服务器仍然能够向所有客户端发送命令。我正在使用“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()
答案 0 :(得分:6)
由于你已经使用了twisted,你也应该将它用于控制台部分,而不是在线程中使用raw_input
。
Twisted的事件循环可以监视任何文件描述符的变化,包括标准输入,因此您可以在输入的新行上获得基于事件的回调 - 它可以异步工作而无需线程。
我发现了这个example of a interactive console in a twisted application,也许你可以使用它。