Getting command line input while listening for connections in Python

I am trying to write a program to which clients connect to it while the server can still send commands to all clients. I am using the โ€œTwistedโ€ solution. How can i do this? Here is the code that I still have (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() 
+6
source share
1 answer

Since you are already using twisted, you should also use it for part of the console instead of using raw_input in the stream.

Twisted event loop can track any file descriptors for changes, including standard input, so you can receive event-based callbacks on a new line entered - it works asynchronously without the need for threads.

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

+6
source

Source: https://habr.com/ru/post/889581/


All Articles