6.23 驱动开发作业

epoll实现并发服务器代码

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

#define ERR_MSG(msg) do{\
    fprintf(stderr, "line:%d ", __LINE__);\
    perror(msg);\
}while(0)

#define IP "192.168.8.61"   //本机IP ifconfig
#define PORT 6666           //1024-49151

int main(int argc, const char *argv[])
{

	  //创建流式套接字
    int sfd = socket(AF_INET, SOCK_STREAM, 0); 
    if(sfd < 0)
    {   
        ERR_MSG("socket");
        return -1; 
    }   
    printf("sfd = %d\n", sfd);

    //允许端口快速重用
    int reuse = 1;
    if(setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0)
    {   
        ERR_MSG("setsockopt");
        return -1; 
    }   
    printf("允许端口快速重用成功\n");

    //填充地址信息结构体,
    //真实的地址信息结构体根据地址族指定 AF_INET:man 7 ip
    struct sockaddr_in sin;
    sin.sin_family      = AF_INET;          //必须填AF_INET;
    sin.sin_port        = htons(PORT) ;     //端口号,1024~49151
    sin.sin_addr.s_addr = inet_addr(IP);    //本机IP, ifconfig

    //将IP和端口绑定到套接字上;
    if(bind(sfd, (struct sockaddr*)&sin, sizeof(sin)) < 0)
    {   
        ERR_MSG("bind");
        return -1; 
    }   
    printf("bind success __%d__\n", __LINE__); 

    //将套接字设置为被动监听状态,监听是否有客户端连接成功;
    if(listen(sfd, 128) < 0)
    {   
        ERR_MSG("listen");
        return -1; 
    }   
    printf("listen success __%d__\n", __LINE__);
	
    int epfd=epoll_create(1);
	if(epfd<0)
    {
        printf("epoll_create err\n");
        exit(-1);
    }

    //将要监听的事件文件描述符添加到epoll中
    event.events=EPOLLIN;
    event.data.fd=sfd;

  	ret=epoll_ctl(epfd, EPOLL_CTL_ADD,sfd,&event);
    if(ret)
    {
        printf("epoll_ctl err\n");
        exit(-1);
    }	
	
	//循环监听
    while(1)
    {
        ret=epoll_wait(epfd,events,10,-1);
        if(ret<0)
        {
            printf("epoll_wait err\n");
            exit(-1);
        }
        
        for(i=0;i

你可能感兴趣的:(数学建模,java,开发语言)