多路复用(五)epoll

服务端

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/epoll.h>

int main()
{
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(6666);
	addr.sin_addr.s_addr = inet_addr("192.168.0.111");
	socklen_t addrlen = sizeof(addr);

	if(bind(sockfd,(struct sockaddr*)&addr,addrlen))
	{
		perror("bind");
		return -1;
	}

	if(listen(sockfd,10))
	{
		perror("listen");
		return -1;
	}
	int epfd = epoll_create(10);
	struct epoll_event event;
	event.data.fd = sockfd;
	event.events = EPOLLIN;
	epoll_ctl(epfd,EPOLL_CTL_ADD,sockfd,&event);
	struct epoll_event* events = calloc(sizeof(struct epoll_event),10);

	for(;;)
	{
		int cnt = epoll_wait(epfd,events,10,100000);
		if(cnt <= 0) continue;
		for(int i=0; i<cnt; i++)
		{
			printf("cnt=%d fd=%d sockfd:%d\n",cnt,events[0].data.fd,sockfd);
			if(events[i].data.fd == sockfd)
			{
				int clifd = accept(sockfd,(struct sockaddr*)&addr,&addrlen);
				if(0 > clifd) continue;
				event.data.fd = clifd;
				event.events = EPOLLIN;
				epoll_ctl(epfd,EPOLL_CTL_ADD,clifd,&event);
			}
			else
			{
				char buf[4096] = {};
				int ret = recv(events[i].data.fd,buf,sizeof(buf),0);
				if(ret <= 0)
				{
					epoll_ctl(epfd,EPOLL_CTL_DEL,events[i].data.fd,events+i);
					continue;
				}

				printf("clifd:%d recv:%s\n",events[i].data.fd,buf);
				send(events[i].data.fd,buf,strlen(buf)+1,1);
			}
		}
	}
}

客户端

#include <stdio.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string.h>

int main()
{
	printf("服务器创建socket...\n");
	int sockfd = socket(AF_INET,SOCK_STREAM,0);
	if(0 > sockfd)
	{
		perror("socket");
		return -1;
	}

	printf("准备地址...\n");
	struct sockaddr_in addr = {};
	addr.sin_family = AF_INET;
	addr.sin_port = htons(7777);
	addr.sin_addr.s_addr = inet_addr("192.168.0.111");
	socklen_t len = sizeof(addr);

	printf("绑定连接服务器...\n");
	if(connect(sockfd,(struct sockaddr*)&addr,len))
	{
		perror("bind");
		return -1;
	}

	for(;;)
	{
			char buf[1024] = {};
			printf(">");
			gets(buf);
			write(sockfd,buf,strlen(buf)+1);
			if(0 == strcmp("quit",buf))
			{
				printf("通信结束!\n");
				break;
			}
			printf("read:");
			read(sockfd,buf,sizeof(buf));
			printf("%s\n",buf);
	}
	close(sockfd);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值