gpt4 book ai didi

python - 使用 python +twisted 的简单服务器中服务客户端的计数器

转载 作者:太空宇宙 更新时间:2023-11-03 19:20:00 25 4
gpt4 key购买 nike

我正在使用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”,我不知道为什么。

谢谢

最佳答案

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() 方法来执行类似的操作。

关于python - 使用 python +twisted 的简单服务器中服务客户端的计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10078564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com