【问题标题】:Receiving commandline input while listening for connections in Python在 Python 中侦听连接时接收命令行输入
【发布时间】:2011-09-06 15:38:40
【问题描述】:

我正在尝试编写一个程序,让客户端连接到它,而服务器仍然能够向所有客户端发送命令。我正在使用“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()

【问题讨论】:

    标签: python sockets client twisted


    【解决方案1】:

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

    Twisted 的事件循环可以监视任何文件描述符的更改,包括标准输入,因此您可以在输入的新行上获得基于事件的回调——它异步工作,无需线程。

    我找到了这个example of a interactive console in a twisted application,也许你可以使用它。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 1970-01-01
    • 2011-12-10
    相关资源
    最近更新 更多