Linux C语言epoll实现echo服务器

使用内核实现的epoll树 

#include <netdb.h>
#include <stdio.h>
#include <sys/socket.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <memory.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#include <sys/epoll.h>



void out_addr(struct sockaddr_in *clientaddr)
{
	int port = ntohs(clientaddr->sin_port);
	char ip[16];
	memset(ip,0,sizeof(ip));
	inet_ntop(AF_INET, &clientaddr->sin_addr.s_addr, ip, sizeof(ip));
	printf("client: %s(%d) connected\n", ip, port);
}

int main(int argc, char *argv[])
{
	if(argc<2){
		printf("usage: %s #port\n", argv[0]);
		exit(1);
	}

	// AF_INET: IPV4
	// SOCK_STREAM: tcp
	int lfd = socket(AF_INET, SOCK_STREAM, 0);
	if(lfd < 0){
		perror("socket error");
		exit(1);
	}
	struct sockaddr_in  serveraddr;

	memset(&serveraddr, 0, sizeof(serveraddr));

	serveraddr.sin_family = AF_INET;
	serveraddr.sin_port = htons(atoi(argv[1]));
	serveraddr.sin_addr.s_addr = INADDR_ANY;
	if(bind(lfd,(struct sockaddr*)&serveraddr,
				sizeof(serveraddr))<0)	{
		perror("bind error");
		exit(1);
	}

	if(listen(lfd,36) <0){
		perror("listen error");
		exit(1);
	}

	printf("Start accept ......\n");

	struct sockaddr_in client_addr;
	socklen_t cli_len = sizeof(client_addr);

	// create root of epoll tree
	int epfd = epoll_create(2000);
	// init epoll tree
	struct epoll_event ev;
	ev.events = EPOLLIN;
	ev.data.fd = lfd;
	epoll_ctl(epfd,EPOLL_CTL_ADD,lfd,&ev);

	struct epoll_event all[2000];
	while(1){

		int ret = epoll_wait(epfd,all,sizeof(all)/sizeof(all[0]),-1);

		for(int i=0;i<ret;i++){
			int fd = all[i].data.fd;
			if(fd==lfd){
                // 客户端发起连接请求
				int cfd = accept(lfd,
					(struct sockaddr*)&client_addr,
				       &cli_len);

				if(cfd == -1){
					perror("accept error");
					exit(1);
				}

                // 将客户端fd挂到epoll树上
				struct epoll_event temp;
				temp.events = EPOLLIN;
				temp.data.fd = cfd;
				epoll_ctl(epfd,EPOLL_CTL_ADD,cfd,&temp);
				out_addr(&client_addr);

			}

			else{
                // 处理逻辑
				if(!all[i].events & EPOLLIN)
					continue;
                // 监听到读事件
				char buf[1024] = {0};
				int len = recv(fd,buf,sizeof(buf),0);
				if(len ==-1){
					perror("recv error");
					exit(1);
				}
				else if(len==0){
                    // 客户端断开连接
					printf("client disconnected ...\n");
					int ret = epoll_ctl(epfd,EPOLL_CTL_DEL,fd,NULL);
					if(ret == -1){
						perror("epoll_ctl - del error");
						exit(1);
					}
					close(fd);
				}

				else{
                    // 接受到数据
					printf(" recv buf:%s",buf);
					write(fd,buf,len);
				}
			}
		}
	
	}

	return 0;

}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值