I have a Twisted socket that I am attempting to run on multiple ports. The following code has worked for me before, but that was around 1 month ago as I have not touched the code since, if I remember right. Now, after re-entering the code into my Twisted program, it doesn’t work anymore.
class Socket(Protocol):
table = Table()
def connectionMade(self):
#self.transport.write("""connected""")
self.factory.clients.append(self)
print "Clients are ", self.factory.clients
def connectionLost(self, reason):
self.factory.clients.remove(self)
def dataReceived(self, data):
#print "data is ", data
a = data.split(':')
if len(a) > 1:
command = a[0]
content = a[1]
if command == "Number_of_Players":
msg = table.numberOfPlayers
print msg
for c in self.factory.clients:
c.message(msg)
def message(self, message):
self.transport.write(message)
NUM_TABLES = 10
factories = [ ]
for i in range(0, NUM_TABLES):
print i
factory = Factory()
factory.protocol = Socket
factory.clients = []
factories.append(factory)
reactor.listenTCP(1025+i, factory)
#print "Blackjack server started"
reactor.run()
It would usually print Blackjack server started however many times in the range I set, but now it doesn’t. To test if it was looping over or not, I set out to print i, but it only printed 0. For some reason, the for loop only looped 1 time.
Any suggestions? Thanks!
Twisted programs usually have only one
reactorrunning. Keep in mind that when you start (.run()) the reactor, execution passes inside the reactor loop (and the various events that you have defined in your code, likeconnectionMade(),connectionLost(),dataReceived(), etc are triggered when the respective actions take place). Whatever code is after thereactor.run()is executed only after reactor is stopped.So, your code never passes the first iteration of the
forloop.Try moving the
reactor.run()out of the loop: