在Python中监听连接时接收命令行输入
我正在尝试写一个程序,让客户端可以连接到它,同时服务器还能向所有客户端发送命令。我正在使用“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()
1 个回答
6
既然你已经在使用twisted了,那就把控制台部分也用twisted来处理,而不是在一个线程里用raw_input
。
twisted的事件循环可以监控任何文件描述符的变化,包括标准输入,这样你就可以在输入新的一行时得到事件回调——它是异步工作的,不需要线程。
我找到一个关于在twisted应用中实现交互式控制台的示例,也许你可以用得上。