def send_ping(self): """Periodically sends a ping and checks if we should close the connection due to the other side timing out. """ now = self.clock.time_msec() if self.time_we_closed: if now - self.time_we_closed > PING_TIMEOUT_MS: logger.info( "[%s] Failed to close connection gracefully, aborting", self.id() ) assert self.transport is not None self.transport.abortConnection() else: if now - self.last_sent_command >= PING_TIME: self.send_command(PingCommand(now)) if ( self.received_ping and now - self.last_received_command > PING_TIMEOUT_MS ): logger.info( "[%s] Connection hasn't received command in %r ms. Closing.", self.id(), now - self.last_received_command, ) self.send_error("ping timeout")
def connectionMade(self): logger.info("[%s] Connection established", self.id()) self.state = ConnectionStates.ESTABLISHED connected_connections.append(self) # Register connection for metrics self.transport.registerProducer(self, True) # For the *Producing callbacks self._send_pending_commands() # Starts sending pings self._send_ping_loop = self.clock.looping_call(self.send_ping, 5000) # Always send the initial PING so that the other side knows that they # can time us out. self.send_command(PingCommand(self.clock.time_msec()))