1

Im using twisted to make a simple server that accepts multiple connections and i want to count the numbers of clients who have been connected. This counting im doing in the factory (as is logical) using clientConnectionMade() but doesn't update the value of the counter, really i dont know where it is my mistake. I appreciate a little help.

My Server code: (also in http://bpaste.net/show/26789/)

 import socket
 import datetime
 from twisted.internet import reactor, protocol
 from twisted.internet.protocol import Factory, Protocol

class Echo(protocol.Protocol):

def connectionMade(self):
    print "New client connected"

def dataReceived(self, data):
    print "Msg from the client received"
    if data == "datetime":
       now = datetime.datetime.now()
       self.transport.write("Date and time:")
       self.transport.write(str(now))
    elif data == "clientes":
       self.transport.write("Numbers of clients served: %d " % (self.factory.numClients))
    else:
       self.transport.write("msg received without actions")

class EchoFactory(Factory):

protocol = Echo

    def __init__(self):
        self.numClients = 0

    def clientConnectionMade(self):
       self.numClients = self.numClients+1

def main():
factory = EchoFactory()
factory.protocol = Echo
reactor.listenTCP(9000,factory)
reactor.run()

 # this only runs if the module was *not* imported
if __name__ == '__main__':
main()

Doesnt show any error, just doesnt update the counter 'numClients' and i dont know why.

Thanks

4

1 回答 1

1

clientConnectionMade(增加 self.numClients)不是 Factory 类的有效方法,因此框架永远不会调用它。

从 Echo.connectionMade() 方法内部调用 self.factory.numClients += 1 将起作用:

class Echo(protocol.Protocol):
    def connectionMade(self):
        print "New client connected"
        self.factory.numClients += 1

你也可以重写你的工厂的 buildProtocol() 方法来做类似的事情。

于 2012-04-10T16:28:11.327 回答