本文介绍了在侦听Python中的连接时接收命令行输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a program that has clients connect to it while the server is still able to send commands to all of the clients. I am using the "Twisted" solution. How can I go about this? Here is the code I have so far (I understand that Twisted already uses non-blocking sockets):

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()

推荐答案

由于您已经在使用Twisted,因此还应该将其用于控制​​台部分,而不是在线程中使用raw_input.

Since you're already using twisted, you should also use it for the console part, instead of using raw_input in a thread.

Twisted的事件循环可以监视任何文件描述符的变化,包括标准输入,因此您可以在输入的新行上获取基于事件的回调-它异步运行而无需线程.

Twisted's event loop can monitor any file descriptor for changes, including the standard input, so you can get event-based callbacks on a new line entered -- It works asynchronously without need for threads.

我找到了一个示例交互应用程序中的交互式控制台,也许您可​​以使用它.

I've found this example of a interactive console in a twisted application, maybe you can use it.

这篇关于在侦听Python中的连接时接收命令行输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 20:00