queen/net/
tcp_ext.rs

1use std::os::unix::io::AsRawFd;
2use std::io;
3
4use queen_io::sys::socket::{setsockopt, getsockopt};
5use queen_io::net::tcp::TcpStream;
6
7pub trait TcpExt: AsRawFd {
8    fn set_keep_alive(&self, enabled: bool) -> io::Result<()> {
9        let en: i32 = if enabled { 1 } else { 0 };
10
11        setsockopt(self.as_raw_fd(), libc::SOL_SOCKET, libc::SO_KEEPALIVE, en)
12    }
13
14    fn keep_alive(&self) -> io::Result<bool> {
15        let ret: i32 = getsockopt(self.as_raw_fd(), libc::SOL_SOCKET, libc::SO_KEEPALIVE)?;
16
17        if ret == 1 { Ok(true) } else { Ok(false) }
18    }
19
20    /// Send first probe after `interval' seconds
21    /// 设置连接上如果没有数据发送的话,多久后发送 keepalive 探测分组,单位是秒
22    fn set_keep_idle(&self, secs: i32) -> io::Result<()> {
23        setsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPIDLE, secs)
24    }
25
26    fn keep_idle(&self) -> io::Result<i32> {
27        getsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPIDLE)
28    }
29
30    /// Send next probes after the specified interval. Note that we set the
31    /// delay as interval / 3, as we send three probes before detecting
32    /// an error (see the next setsockopt call). */
33    /// 前后两次探测之间的时间间隔,单位是秒
34    fn set_keep_intvl(&self, secs: i32) -> io::Result<()> {
35        setsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPINTVL, secs)
36    }
37
38    fn keep_intvl(&self) -> io::Result<i32> {
39        getsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPINTVL)
40    }
41
42    /// Consider the socket in error state after three we send three ACK
43    /// probes without getting a reply. */
44    /// 关闭一个非活跃连接之前的最大重试次数
45    fn set_keep_cnt(&self, count: i32) -> io::Result<()> {
46        setsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPCNT, count)
47    }
48
49    fn keep_cnt(&self) -> io::Result<i32> {
50        getsockopt(self.as_raw_fd(), libc::SOL_TCP, libc::TCP_KEEPCNT)
51    }
52}
53
54impl TcpExt for TcpStream {}