Reputation: 125
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()
Upvotes: 6
Views: 1629
Reputation: 222922
Since you're already using twisted, you should also use it for the console part, instead of using raw_input
in a thread.
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.
Upvotes: 6