Skip to main content
 首页 » 编程设计

python之在 python twisted 中实现超时

2024年11月01日15三少

据我所知,twisted 是异步和事件驱动的,有人告诉我他们不需要超时。我必须构建一个服务器应用程序,它将连接到 100 多个客户端,这些客户端是嵌入式机器,每 2 分钟向服务器发送一次数据,每个数据包或数据的大小为 238 - 1500 字节。因此,在现实生活中,tcp 会将数据分成多个数据包,因此他们是否需要实现超时或扭曲来处理这种情况。任何建议,因为我是新的扭曲。我的服务器有以下代码,没有超时。在超时结束时,如果在连接保持事件状态时未收到完整数据包,我只想丢弃数据包。

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() 

请您参考如下方法:

正如@Ashish Nitin Patil 所建议的那样,只需切断连接即可实现超时:

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

或者

At the end of timeout I just want to discard packet if full packet is not received while connection remains alive.

如果您不想在超时时取消连接,那么:

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