赞
踩
最近在整一个监控后台开发,就涉及到了检查TCP连接是否失效的问题,所以学习过后,在此总结一下。
刚接触TCP编程的人,比如我学了半年,还没有意识到这个问题,只有在项目中遇到了,才开始思考,在没有读写的连接中,有哪些TCP连接上有效的,哪些连接上无效的。比如客户端突然崩溃,服务器端可能在几天内都维护着一个无用的TCP连接。
那么TCP自己有没有类似”轮询“的机制,让它告诉我们,连接还”活着“呢?
实际上,TCP确实有一个保持活跃的机制叫做”Keep-Alive“。该机制原理如下:
定义一个时间段,在这个时间段内,如果没有任何连接相关的活动,TCP 保活机制会开始作用,每隔一个时间间隔,发送一个探测报文,该探测报文包含的数据非常少,如果连续几个探测报文都没有得到响应,则认为当前的 TCP 连接已经死亡,系统内核将错误信息通知给上层应用程序。
上述的可定义变量,分别被称为保活时间、保活时间间隔和保活探测次数。在 Linux 系统中,这些变量分别对应 sysctl 变量net.ipv4.tcp_keepalive_time、net.ipv4.tcp_keepalive_intvl、 net.ipv4.tcp_keepalve_probes,默认设置是 7200 秒(2 小时)、75 秒和 9 次探测。
如果开启了TCP保活,需要考虑以下几种情况:
TCP 保活机制默认是关闭的,当我们选择打开时,可以分别在连接的两个方向上开启,也可以单独在一个方向上开启。如果开启服务器端到客户端的检测,就可以在客户端非正常断连的情况下清除在服务器端保留的“脏数据”;而开启客户端到服务器端的检测,就可以在服务器无响应的情况下,重新发起连接。
相信你也发现,TCP提供的保活机制,默认的频率好低。其实这是因为早期的网络带宽非常有限,如果提供一个频率高的保活机制,对有限的带宽是比较浪费的。
很容易想到,TCP自身的Keep-Alive机制基本上满足不了现在都业务需求,对于很多对时延要求敏感的系统来说,这个探活的时间间隔是不可接受的。
那么,我们就需要在应用层来寻找解决方案,其实方案也很简单,仿照TCP Keep-Alive机制,只需将保活时间、时间间隔、保活探测次数设为合适的值,即可满足各种应用场景。设计方案如下:
我们可以设计一个 PING-PONG 的机制,需要保活的一方,比如客户端,在保活时间达到后,发起对连接的 PING 操作,如果服务器端对 PING 操作有回应,则重新设置保活时间,否则对探测次数进行计数,如果最终探测次数达到了保活探测次数预先设置的值之后,则认为连接已经无效。
这里有两个比较关键的点:第一个是需要使用定时器,这可以通过使用 I/O 复用自身的机制来实现;第二个是需要设计一个 PING-PONG 的协议。
以下给出了代码的实现,可以通过设置服务端的睡眠时间,模拟服务端响应的时间,这样客户端的保活机制就会出现不一样的情况。
针对保活,设计了如下的消息对象:
#ifndef MESSAGE_H
#define MESSAGE_H
typedef struct
{
int type;
char data[1024];
} messageObject;
#define MSG_PING 1
#define MSG_PONG 2
#define MSG_TYPE1 11
#define MSG_TYPE2 21
#endif // MESSAGE_H
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <strings.h> /* for bzero() */ #include <errno.h> #include <time.h> #include <unistd.h> #include <iostream> #include "message.h" #define SERV_PORT 12345 #define LISTENQ 1024 static int count; int main(int argc, char **argv) { if (argc != 2) { perror("usage: tcpsever <sleepingtime>"); } int sleepingTime = atoi(argv[1]); int listenfd; listenfd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(SERV_PORT); int rt1 = bind(listenfd, (struct sockaddr *)&server_addr, sizeof(server_addr)); if (rt1 < 0) { perror("bind failed "); } int rt2 = listen(listenfd, LISTENQ); if (rt2 < 0) { perror("listen failed "); } int connfd; struct sockaddr_in client_addr; socklen_t client_len = sizeof(client_addr); if ((connfd = accept(listenfd, (struct sockaddr *)&client_addr, &client_len)) < 0) { perror("bind failed "); } messageObject message; count = 0; for (;;) { int n = read(connfd, (char *)&message, sizeof(messageObject)); if (n < 0) { perror("error read"); } else if (n == 0) { perror("client closed \n"); } printf("received %d bytes\n", n); count++; switch (ntohl(message.type)) { case MSG_TYPE1: printf("process MSG_TYPE1 \n"); break; case MSG_TYPE2: printf("process MSG_TYPE2 \n"); break; case MSG_PING: { messageObject pong_message; pong_message.type = MSG_PONG; sleep(sleepingTime); ssize_t rc = send(connfd, (char *)&pong_message, sizeof(pong_message), 0); if (rc < 0) perror("send failure"); break; } default: perror("unknown message type\n"); } } }
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/select.h> /* for select() */ #include <strings.h> /* for bzero() */ #include <errno.h> #include <time.h> #include <unistd.h> #include <iostream> #include "message.h" #define MAXLINE 4096 #define KEEP_ALIVE_TIME 10 #define KEEP_ALIVE_INTERVAL 3 #define KEEP_ALIVE_PROBETIMES 3 #define SERV_PORT 12345 int main(int argc, char **argv) { if (argc != 2) { perror("usage: tcpclient <IPaddress>"); } int socket_fd; socket_fd = socket(AF_INET, SOCK_STREAM, 0); struct sockaddr_in server_addr; bzero(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(SERV_PORT); inet_pton(AF_INET, argv[1], &server_addr.sin_addr); socklen_t server_len = sizeof(server_addr); int connect_rt = connect(socket_fd, (struct sockaddr *)&server_addr, server_len); if (connect_rt < 0) { perror("connect failed "); } char recv_line[MAXLINE + 1]; int n; fd_set readmask; fd_set allreads; struct timeval tv; int heartbeats = 0; tv.tv_sec = KEEP_ALIVE_TIME; tv.tv_usec = 0; messageObject messageObject; FD_ZERO(&allreads); FD_SET(socket_fd, &allreads); for (;;) { readmask = allreads; int rc = select(socket_fd + 1, &readmask, NULL, NULL, &tv); if (rc < 0) { perror("select failed"); } if (rc == 0) { if (++heartbeats > KEEP_ALIVE_PROBETIMES) { perror("connection dead\n"); } printf("sending heartbeat #%d\n", heartbeats); messageObject.type = htonl(MSG_PING); rc = send(socket_fd, (char *)&messageObject, sizeof(messageObject), 0); if (rc < 0) { perror("send failure"); } tv.tv_sec = KEEP_ALIVE_INTERVAL; continue; } if (FD_ISSET(socket_fd, &readmask)) { n = read(socket_fd, recv_line, MAXLINE); if (n < 0) { perror("read error"); } else if (n == 0) { perror("server terminated"); } printf("received heartbeat, make heartbeats to 0 \n"); heartbeats = 0; tv.tv_sec = KEEP_ALIVE_TIME; } } }
客户端需要注意的,主要有两部分
第一部分,这里为select设置了定时器:
第二部分,心跳报文处理:
虽然 TCP 没有提供系统的保活能力,让应用程序可以方便地感知连接的存活,但是,我们可以在应用程序里灵活地建立这种机制。一般来说,这种机制的建立依赖于系统定时器,以及恰当的应用层报文协议。比如,使用心跳包就是这样一种保持 Keep Alive 的机制。
问题一:TCP的探活是否适用于UDP呢?
udp不需要连接 所以没有必要心跳包
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。