2012-04-09 34 views
1

即時通訊使用扭曲,使一個簡單的服務器,接受多個連接,我想統計已連接的客戶端的數量。這個計數即時在工廠(使用clientConnectionMade()邏輯),但不會更新計數器的值,我真的不知道它在哪裏是我的錯誤。我讚賞一點幫助。計數器服務客戶端在一個簡單的服務器使用Python +扭曲

我的服務器代碼:(也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」,我不知道爲什麼。

感謝

+0

這個編譯?你的間隔是不正確的... – Ben 2012-04-09 20:15:04

回答

1

clientConnectionMade(你增加self.numClients)是not a valid method on the Factory class,所以它永遠不會被框架調用。

調用self.factory.numClients +從Echo.connectionMade內部= 1()方法將工作:

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

你也可以重寫你的工廠的buildProtocol()方法做同樣的事情。

+0

感謝fmoo,但沒有工作,因爲connectionmade被調用一次,所以numclients更新到1,並保持在那裏。事實上,這是我的第一個代碼,我認爲客戶的數量必須在工廠。 – boogieman 2012-04-11 16:28:27

相關問題