2013-11-15 52 views
2

據我所知,twisted是異步和事件驅動的,有人告訴我他們不需要超時。我必須構建一個服務器應用程序,它將連接到100多個客戶端,這些客戶端是每2分鐘向服務器發送數據的嵌入式機器,每個數據包或數據的大小爲238 - 1500字節。因此,現實生活中,tcp會將數據分成多個數據包,因此他們需要執行超時或扭曲處理這種情況。任何建議,因爲我是新的扭曲。我有沒有超時我的服務器的以下代碼。在超時結束時,我只想丟棄數據包,如果在連接保持活動狀態時沒有收到完整數據包。在Python中實現超時扭曲

class Server(LineReceiver): 

    def connectionMade(self): 
    self.factory.clients.append(self) 
    self.setRawMode() 
    self._peer = self.transport.getPeer() 
    print 'Connected Client', self._peer 

    def connectionLost(self, reason): 
    self.factory.clients.remove(self) 
    print 'Lost connection from', self._peer 

    def rawDataReceived(self, data): 
    inputArray = [ord(inp) for inp in data] 
    #do something 



def main(): 
    """This runs the protocol on port 8000""" 
    factory = protocol.ServerFactory() 
    factory.protocol = Server 
    factory.clients = [] 
    reactor.listenTCP(8000,factory) 
    reactor.run() 
+0

做一個函數,它不連接的削減。在主要功能中,記錄時間(s),何時觸發該功能(s)? –

+0

您是否嘗試發送大小爲「238 - 1500字節」的數據?結果是什麼? – softvar

+0

我在c#中創建了一個類似的應用程序,並且沒有超時測試我能夠接收完整的數據包,但它僅用2-3個客戶端進行了測試,但是如果他們的超過100-1000個客戶端每2分鐘發送一次數據,那麼我認爲他們是需要超時。也許我錯了?糾正我。 – prattom

回答

2

由於@Ashish尼廷·帕蒂爾建議,只是削減的連接來實現超時:

from twisted.internet import reactor 

# ... 
def connectionMade(self): 
    # ... your code 
    # cancel connection in 2 minutes 
    reactor.callLater(120, self.transport.loseConnection) 

或者

在超時結束時,我只是想,如果完全丟棄數據包在連接保持活動狀態時未收到數據包。

如果你不想取消超時連接,然後:

from time import time as timer 

def connectionMade(self): 
    # ... your code 
    self.endtime = timer() + 120 # timeout in 2 minutes 

def dataReceived(self, data): 
    if timer() > self.endtime: # timeout 
     if not self.have_we_received_full_packet() 
      return # do nothing (discard data, the connection remains alive) 
     else: 
      # timeout happened but we have a full packet, now what? 
    inputArray = bytearray(data) 
    #do something