0

I've been trying to make a sever that multiple clients can connect to but I ran into a problem. I have a list with all the current connected targets and I want to check if they're still alive without having to manually connect to them.

This is the listener method from the Class I've written:

def listenForConnections(self):
        self.s.bind((self.HOST, self.PORT)) 
        while True:
            self.s.listen(128)
            c, addr = self.s.accept()
            self.c = c
            print("\n[+]Got a new connection!")
            self.conns.append(c)

As you can see, it appends a new connection object to a list from which you then can select a target with a getTarget() method from the same class but I won't paste it here since you probably know how it looks like. Keep in mind that the listener runs in a separate thread. Now I would like to write a ping() function of a sort, that checks every couple of seconds, if all the connections in the conns list are still alive but I have no idea how to do it. I thought in the ping method I would have to send some data to the client every couple of seconds but I fear that it would break the whole program because it could be that the client think that it's a valid command sent from the user and not some garbage to check if a connection is alive or not.

b.tchman
  • 112
  • 2
  • 12
  • 1
    Possible duplicate of [How to tell if a connection is dead in python](https://stackoverflow.com/questions/667640/how-to-tell-if-a-connection-is-dead-in-python) – Iain Shelvington Sep 27 '19 at 05:11

1 Answers1

0

If you want to use a PING message to detect if the client is still alive then you have to provide for this in the client/server protocol. As you noted already, the client must be able to see it is a PING message and not a "normal" message. This only works if you can change the client/server protocol. This is more difficult to implement if the client/server protocol is strictly request/response based, as now the server can also initiate messages.

There are other options:

  • If the client closes the connection correctly, the server can determine this the next time it tries to communicate with the client.
  • If the client normally sends requests continuously, you can assume the client is dead and close the connection if the client has not send new requests for some time.
  • You can use TCP/IP keepalive to detect dead clients.
rveerd
  • 3,620
  • 1
  • 14
  • 30