栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

发送端三个新函数
#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);
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/916892.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号