epoll一点思考(3)

本文探讨了epoll中in事件触发的三种情况:客户端发送数据、部分读取后无新数据、客户端关闭连接(包括拔掉网线、断电)。在不同情况下,epoll的in和out事件如何响应,并涉及了keep-alive对事件的影响。
摘要由CSDN通过智能技术生成

epoll in事件触发时机


第一种情况,当设置了in,并且客户端发送数据到达会触发in事件

第二种情况,设置in,但是客户端发送数据100字节,服务器读取20字节,不再触发in直到再次设置in或有新数据到达。

第三种情况,设置in,如果client关闭(close socket或程序关闭),会触发in事件,recv返回0,如果没有del掉event,并且设置out事件,会触发out事件,如果一直在设置(询问)in事件,则会一直收到in事件。对于拔掉网线与断电情况,recv返回-1,erron为ETIMEOUT,如果没有设置keep-alive不会触发in事件,如果设置了keep-alive会触发一次in事件,但是在接收in事件后设置out事件后不会触发out事件。


第三种情况,没有设置keep-alive,客户端close socket或程序关闭

#include <iostream>
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <netinet/tcp.h>

using namespace std;

#define MAXLINE 5
#define OPEN_MAX 100
#define LISTENQ 20
#define SERV_PORT 6002
#define INFTIM 1000

int socket_set_keepalive( int fd)
{
    int ret, error, flag, alive, idle, cnt, intv;
    
    /* Set: use keepalive on fd */
    alive = 1;
    if (setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE, &alive, sizeof alive) != 0)
    {
        printf ("Set keepalive error: %s.\n" , strerror (errno));
        return -1;
    }
    
    /* 10秒钟无数据,触发保活机制,发送保活包 */
    idle = 10;
    if (setsockopt(fd, SOL_TCP, TCP_KEEPIDLE , &idle, sizeof idle) != 0)
    {
        printf ("Set keepalive idle error: %s.\n" , strerror (errno));
        return -1;
    }
    
    /* 如果没有收到回应,则5秒钟后重发保活包 */
    intv = 5;
    if (setsockopt(fd, SOL_TCP, TCP_KEEPINTVL , &intv, sizeof intv) != 0)
    {
        printf ("Set keepalive intv error: %s.\n", strerror (errno));
        return -1;
    }
    
    /* 连续3次没收到保活包,视为连接失效 */
    cnt = 3;
    if (setsockopt(fd, SOL_TCP, TCP_KEEPCNT , &cnt, sizeof cnt) != 0)
    {
        printf ("Set keepalive cnt error: %s.\n", strerror (errno));
        return -1;
    }
    
    return 0;
}


void setnonblocking(int sock)
{
    int opts;
    opts=fcntl(sock,F_GETFL);
    if(opts<0)
    {
        perror("fcntl(sock,GETFL)");
        exit(1);
    }
    opts = opts|O_NONBLOCK;
    if(fcntl(sock,F_SETFL,opts)<0)
    {
        perror("fcntl(sock,SETFL,opts)");
        exit(1);
    }   
}

int main()
{
    int i, maxi, listenfd, connfd, sockfd,epfd,nfds;
    ssize_t n;
    char line[MAXLINE];
    socklen_t clilen;
    //声明epoll_event结构体的变量,ev用于注册事件,数组用于回传要处理的事件
  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值