使用python + twisted在一个简单的服务器中服务客户的计数器

时间:2012-04-09 19:23:51

标签: python twisted

我使用twisted制作一个接受多个连接的简单服务器,我想计算已连接的客户端数量。这个使用clientConnectionMade()在工厂里进行计数(虽然是合乎逻辑的),但不更新计数器的值,我真的不知道这是我的错误。我很感激一点帮助。

我的服务器代码:(也在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()

不显示任何错误,只是不更新​​计数器'numClients',我不知道为什么。

由于

1 个答案:

答案 0 :(得分:1)

clientConnectionMade(你增加self.numClients的地方)是not a valid method on the Factory class,所以框架永远不会调用它。

从Echo.connectionMade()方法内部调用self.factory.numClients + = 1可行:

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

您也可以覆盖Factory的buildProtocol()方法来执行类似的操作。