如何在 java 或 netty 中设置套接字选项(TCP_KEEPCNT、TCP_KEEPIDLE、TCP_KEEPINTVL)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22472844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set socket option (TCP_KEEPCNT, TCP_KEEPIDLE, TCP_KEEPINTVL) in java or netty?
提问by Yang Juven
In C/Linux, it's easily to set different value about those socket options for every KEEPALIVEtcp connection independently.
在 C/Linux 中,很容易为每个KEEPALIVEtcp 连接独立地设置有关这些套接字选项的不同值。
TCP_KEEPCNT (since Linux 2.4) The maximum number of keepalive probes TCP should send before dropping the connection. This option should not be used in code intended to be portable.
TCP_KEEPIDLE (since Linux 2.4) The time (in seconds) the connection needs to remain idle before TCP starts sending keepalive probes, if the socket option SO_KEEPALIVE has been set on this socket. This option should not be used in code intended to be portable.
TCP_KEEPINTVL (since Linux 2.4) The time (in seconds) between individual keepalive probes. This option should not be used in code intended to be portable.
TCP_KEEPCNT(自 Linux 2.4 起) TCP 在断开连接之前应发送的最大保持活动探测数。不应在旨在可移植的代码中使用此选项。
TCP_KEEPIDLE(自 Linux 2.4 起) 如果已在此套接字上设置了套接字选项 SO_KEEPALIVE,则在 TCP 开始发送保持活动探测之前连接需要保持空闲的时间(以秒为单位)。不应在旨在可移植的代码中使用此选项。
TCP_KEEPINTVL(自 Linux 2.4 起)单个 keepalive 探测之间的时间(以秒为单位)。不应在旨在可移植的代码中使用此选项。
In netty or java, how to set the three socket options for socket? I know there is no portable way to solve it, but only in Linux, can I set those socket options?
在netty或java中,如何设置socket的三个socket选项?我知道没有可移植的方法来解决它,但只有在 Linux 中,我可以设置那些套接字选项吗?
回答by abligh
回答by paprika
Recent versions of Netty allow you to use epoll type channels and set Linux-native socket options such as the ones you mentioned.
最近版本的 Netty 允许您使用 epoll 类型通道并设置 Linux 原生套接字选项,例如您提到的那些。
See the documentation of EpollChannelOptionfor details.
有关详细信息,请参阅EpollChannelOption的文档。
回答by Lachlan
It appears this is supported in Java 11, via new fields in the ExtendedSocketOptions
class. These can be passed to the setOption
method on either java.net.Socket
or java.nio.channels.SocketChannel
.
Java 11 似乎通过类中的新字段ExtendedSocketOptions
支持这一点。这些可以传递给或setOption
上的方法。java.net.Socket
java.nio.channels.SocketChannel
Note I have not actually tried using this. The docs explicitly say these are platform specific, so you'll need to test they actually do what you want on the platforms you care about.
注意我实际上并没有尝试使用它。文档明确指出这些是特定于平台的,因此您需要测试它们是否在您关心的平台上实际执行您想要的操作。
import java.net.Socket;
import jdk.net.ExtendedSocketOptions;
Socket socket = new Socket();
socket.setOption(ExtendedSocketOptions.TCP_KEEPIDLE, 10);
socket.setOption(ExtendedSocketOptions.TCP_KEEPCOUNT, 2);
socket.setOption(ExtendedSocketOptions.TCP_KEEPINTERVAL, 3);