Unix网络编程-TCP心跳包的实现(使用紧急数据)

Unix网络编程-TCP心跳包的实现(使用紧急数据),第1张

发送端三个新函数
/**
 * @file heartbeatcli.c
 * 紧急数据实现心跳包
 */
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
static int sockfd;  // 套接字
static int nsec;    // 每次定时的秒数,>=1
static int maxnprobes;  // 最大的等待回应的次数
static int nprobes;     // 当前回应的次数,如果等待max没有回应,断开连接

void sig_urg(int signo)
{
    int n;
    char c;
    if ((n = recv(sockfd, &c, 1, MSG_OOB)) < 0)
    {
        if (errno != EWOULDBLOCK)
        {
            perror("recv");
            exit(-1);
        }
    }
    // 正常收到对方的回应,就重置计数器
    nprobes = 0;
    return;
}
void sig_alrm(int signo)
{
    // 如果到达最大次数还没收到回应,就退出
    if (++nprobes > maxnprobes)
    {
        fprintf(stderr, "server is unreachable.\n");
        exit(0);
    }
    // 每一秒发送一个紧急数据
    send(sockfd, "1", 1, MSG_OOB);
    // 重新设置定时器,使用一次之后会失效
    alarm(nsec);
    return;
}

// 设置并启动心跳函数
void heartbeat_cli(int fd, int nsec_arg, int maxnprobes_arg)
{
    sockfd = fd;
    nsec = nsec_arg;
    if (nsec < 1)
    {
        nsec = 1;
    }
    maxnprobes = maxnprobes_arg;
    if (maxnprobes < nsec)
    {
        maxnprobes = nsec;
    }

    nprobes = 0;

    signal(SIGURG, sig_urg);
    fcntl(sockfd, F_SETOWN, getpid());

    signal(SIGALRM, sig_alrm);
    alarm(nsec);
}

接收端三个新函数
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
static int sockfd;  // 套接字
static int nsec;    // 每次定时的秒数,>=1
static int maxnprobes;  // 最大的等待回应的次数
static int nprobes;     // 当前回应的次数,如果等待max没有回应,断开连接

void sig_urg(int signo)
{
    int n;
    char c;
    if ((n = recv(sockfd, &c, 1, MSG_OOB)) < 0)
    {
        if (errno != EWOULDBLOCK)
        {
            perror("recv");
            exit(-1);
        }
    }
    // 正常收到对方的回应,就回复一个
    send(sockfd, &c, 1, MSG_OOB);
    // 重置计数器
    nprobes = 0;
    return;
}
void sig_alrm(int signo)
{
    // 如果到达最大次数还没收到回应,就退出
    if (++nprobes > maxnprobes)
    {
        fprintf(stderr, "server is unreachable.\n");
        exit(0);
    }
    // 重新设置定时器,使用一次之后会失效
    alarm(nsec);
    return;
}

// 设置并启动心跳函数
void heartbeat_serv(int fd, int nsec_arg, int maxnprobes_arg)
{
    sockfd = fd;
    nsec = nsec_arg;
    if (nsec < 1)
    {
        nsec = 1;
    }
    maxnprobes = maxnprobes_arg;
    if (maxnprobes < nsec)
    {
        maxnprobes = nsec;
    }

    nprobes = 0;

    signal(SIGURG, sig_urg);
    fcntl(sockfd, F_SETOWN, getpid());

    signal(SIGALRM, sig_alrm);
    alarm(nsec);
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1295971.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-10
下一篇 2022-06-10

发表评论

登录后才能评论

评论列表(0条)

保存