Reactor.run冻结循环

Ale*_*lec 2 python twisted

我有一个Twisted套接字,我试图在多个端口上运行.以下代码之前对我有用,但那是大约1个月前,因为我没有触及代码,因为我记得正确.现在,在将代码重新输入我的Twisted程序后,它不再起作用了.

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()
Run Code Online (Sandbox Code Playgroud)

它通常会在我设置的范围内多次打印Blackjack服务器,但现在却没有.为了测试它是否循环,我开始打印i,但它只打印0.由于某种原因,for循环只循环1次.

有什么建议?谢谢!

ype*_*eᵀᴹ 5

扭曲的程序通常只有一个reactor运行.请记住,当你开始(.run())反应器,执行反应器循环内传递(和您在您的代码已经定义了各种活动,如connectionMade(),connectionLost(),dataReceived(),等是当相应的动作发生触发).无论代码是在反应堆停止后reactor.run()执行的.

因此,您的代码永远不会通过for循环的第一次迭代.

尝试移出reactor.run()循环:

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

# whatever code you put here, is executed only **after reactor has stopped**
Run Code Online (Sandbox Code Playgroud)