twisted 注意事项 keepalive 断网

每当twisted作为服务器,客户端断网时,twisted不会触发connectionlost方法,解决办法是:

 

def connectionMade(self):
  try:
    self.transport.setTcpKeepAlive(1)  #保活机制,还要调整系统的keepalive
  except AttributeError: pass

 

 

Why isn't my connectionLost method called?

 

connectionLost is called when the platform notifies Twisted that the TCP connection has been closed. TCP connections are closed in one of two ways. They can either be closed "actively" - by one side of the connection sending a close message to the other side - or they can be closed by timeout - one side deciding that the other side has taken too long to respond and interpreting this to mean that the other side is no longer paying attention to the connection. However, for the timeout case, it is important to understand that if an application is not sending data over the connection, there is no response to take too long so no timeout will ever occur. This means that if a network error disrupts a connection but the application is not sending data over it, it's possible for connectionLost to never be called. However, if the application is sending data over it, then the timeout will eventually expire. TCP uses very large timeouts in order to account for very poor networks. If you rely on TCP timeouts, expect as much as two hours (the precise amount is platform specific) to pass between when the disruption occurs and when connectionLost is called. If this is too long, you may want to use an application-level keep alive mechanism to discover lost connections earlier. This just involves sending simple messages back and forth over a connection. If it ever takes longer than whatever amount of time you decide is appropriate for your application to receive a response to one of these messages, consider the connection lost.

Also, keep in mind that transport.loseConnection() may not result in the connection closing immediately, e.g. if you have writes buffered. To close the connection immediately, discarding any buffered writes, call transport.abortConnection().


分享到: 微信 更多