1

In my project, there is a 2 sided connection based on a TCP protocol. One waits for information (PC), and the other one sends it (phone).

I have noticed that if I change the phone's WiFi connection (IP address) while a connection between the devices is alive, the PC side has no idea that the phone has disconnected already.

I think it is called a half opened connection, and as far as I understood, the PC side has to send some empty message in order to detect the disconnection, yet I can't manage to do that. I tried using socket.send("".encode("utf-8")), but it didn't seem to invoke any error.

Is the connection still alive, even if one side is disconnected? And how can the PC detect this issue with Python?

Also, what happens if I send informationg from a socket (in a different thread), while the recv command is running?

Daniel Reyhanian
  • 579
  • 4
  • 26
  • Interestingly you answered both of your questions before asking then. – Klaus D. Jan 06 '20 at 21:06
  • @KlausD. Updated. – Daniel Reyhanian Jan 06 '20 at 21:10
  • Unlike UDP, there is no such thing as empty messages in TCP. You can't send 0 bytes of data in TCP. What you can do instead is enable TCP-level keep-alives and let them detect dead connections for you. Use `socket.setsockopt(SOL_SOCKET, SO_KEEPALIVE, 1)` to enable TCP keepalives – Remy Lebeau Jan 06 '20 at 22:52
  • @RemyLebeau Thank you for the comment, but it doesn't seem to work. Am I supposed to implement anything else? – Daniel Reyhanian Jan 07 '20 at 19:32
  • @DanielReyhanian TCP keep-alives work just fine. It just may take some time for the probes to determine that the connection is dead. `SO_KEEPALIVE` itself doesn't let you configure the time intervals used by the probes, butt on some systems you can use the `TCP_KEEPCNT`, `TCP_KEEPIDLE`, and `TCP_KEEPINTVL` socket options for that. See [TCP Keepalive HOWTO](https://www.tldp.org/HOWTO/html_single/TCP-Keepalive-HOWTO/) for more details. Once keepalives are enabled, all you have to do is continue reading from the connection until it eventually fails, then close the socket. – Remy Lebeau Jan 07 '20 at 19:38
  • @RemyLebeau Reading? Or sending? Because it seems to work only if I send data. – Daniel Reyhanian Jan 07 '20 at 19:48
  • @DanielReyhanian your phone app never reads data from the PC? Only sends to the PC? Well, even so, sending will eventually fail too, once the probing determines the connection is dead and invalidates the socket. – Remy Lebeau Jan 07 '20 at 19:51

0 Answers0