Home > Java > javaTutorial > body text

How Does TCP Keep-Alive Prevent Stale Socket Connections?

Mary-Kate Olsen
Release: 2024-10-26 08:42:30
Original
874 people have browsed it

How Does TCP Keep-Alive Prevent Stale Socket Connections?

Does a TCP Socket Connection Have a "Keep Alive"?

Yes, there is a timeout mechanism in place for TCP socket connections called TCP Keep-Alive. It prevents socket connections from remaining open indefinitely, addressing scenarios where one side terminates the connection without notifying the other.

TCP Keep-Alive Process

TCP Keep-Alive is configurable on Linux through the following properties:

  • tcp_keepalive_time (default: 7200 seconds)
  • tcp_keepalive_probes (default: 9)
  • tcp_keepalive_intvl (default: 75 seconds)

The process involves sending empty ACK packets at regular intervals until a response is received. If no response is received after a specified number of probes, the connection is terminated.

Implementation Notes

Keep-Alive packets are optional and may not be reliably transmitted. However, in practice, most operating systems and cloud providers support this mechanism.

Changing TCP Timeouts

Per Socket Configuration (Java 11 and above):

Java 11 introduced the ability to configure TCP timeouts on a per-socket level using native code.

System-Wide Configuration:

For older versions of Java and on other operating systems, you may have to apply timeout configuration at the system level.

Linux:

# Echo commands to modify the values in /proc
echo 180 > /proc/sys/net/ipv4/tcp_keepalive_time
echo 3 > /proc/sys/net/ipv4/tcp_keepalive_probes
echo 10 > /proc/sys/net/ipv4/tcp_keepalive_intvl
Copy after login

Mac OS X:

# Use sysctl to modify values
sysctl -w net.inet.tcp.keepidle=180000 net.inet.tcp.keepintvl=10000 net.inet.tcp.keepcnt=3
Copy after login

Windows:

Registry key: HKEY_LOCAL_MACHINESystemCurrentControlSetServicesTCPIPParameters

The above is the detailed content of How Does TCP Keep-Alive Prevent Stale Socket Connections?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!