user3578984
user3578984

Reputation:

Detecting when socket gets disconnected via sock.recv and socket.timeout

I have this function to detect state of socket connection (connected or disconnected):

def connection_status(self):

        try:

            sock.settimeout(2)
            connection_status = sock.recv(32)
            print("Status: Connected")
            self.label_connection_status['text'] = 'Status: Connected'
            self.label_connection_status['fg'] = 'green'

        except socket.timeout:

            connection_status = ""
            print("Status: Disconnected")
            self.label_connection_status['text'] = 'Status: Disconnected'
            self.label_connection_status['fg'] = 'red'

        self.master.after(3000, self.connection_status)

But there is a problem with it. When I connects to server (in my case Samsung TV, its remote control application), it few times spam "Status: Connected", but after some seconds it changes to "Status: Disconnected" (but is still connected...), and if I send some data to the server (Samsung TV), it again changes to "Connected" and after few seconds it again changes to "Disconnected". And id I stop the server (Samsung TV), it only outputs "Status: Connected"!

Upvotes: 0

Views: 1079

Answers (1)

SergeyA
SergeyA

Reputation: 62593

Why are you confusing recv() with connection/disconnection? recv() interrupted by timeout simply means there was no data received during specified time frame, but by no means it indicates a disconnection! On the contrary, graceful disconnection will NOT manifest itself as a timeout on recv(), instead, it would be a return from recv() with approriate status, indicating a disconnecting event.

Upvotes: 1

Related Questions