2015-08-20 117 views
0

我正在寫一個簡單的網絡服務器應用程序使用扭曲。應用程序將獲得一個字符串並返回它接收的字符串的反向。扭曲的關閉網絡服務器連接

這一切正常。現在我需要關閉套接字連接,如果5分鐘不活動。

這裏是我的服務器代碼: -

from twisted.internet import reactor, protocol 


class Echo(protocol.Protocol): 
    """This is just about the simplest possible protocol""" 

    def dataReceived(self, data): 
     "As soon as any data is received, write it back." 
     self.transport.write(data[::-1]) 


def main(): 
    """This runs the protocol on port 8000""" 
    factory = protocol.ServerFactory() 
    factory.protocol = Echo 
    reactor.listenTCP(8000,factory) 
    reactor.run() 

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

https://stackoverflow.com/q/11911453/892383 – Cyphase

回答

1

將這些方法添加到您的類:

def connectionMade(self): 
    def terminate(): 
     self.terminateLater = None 
     self.transport.abortConnection() 
    self.terminateLater = reactor.callLater(60 * 5, terminate) 

def connectionLost(self, reason): 
    delayedCall = self.terminateLater 
    self.terminateLater = None 
    if delayedCall is not None: 
     delayedCall.cancel() 

這就使得建立連接時,您的協議將安排一個定時呼叫在5分鐘內關閉連接。如果連接關閉,否則它將取消超時。