相较于之前的select和poll实现改为epoll实现多路复用,理论上在高并发情况下性能将会有显著提升提升。
select,poll,epoll区别
sellect和poll为轮询式,select采用fd数组来存储文件描述符,存在最大数量限制1024,但poll采用poll结构体链表存储,无最大限制,epoll底层采用红黑树存储,且不再使用轮询式获取消息,轮询式可理解为不断询问是否有新消息发送进来,但epoll为中断式,在得到消息发送进来时进行中断处理。当tcp通信,收到客户端数据后在返回ACK确认时,进行处理。
epoll实现简易聊天室案例
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/select.h>
#include <unistd.h>
#include <map>
#include <set>
#include <iostream>
#include <poll.h>
#include <sys/epoll.h>
#define PORT 12344
#define SIP "192.168.0.231" // 服务器本地ip
#define NUM 100
int sockfd;
char buf[1024];
char sbuf[2048];
std::map<int, std::string> mp;
struct epoll_event evs[100];
int epfd;
std::set<int> cfds;
// 将信息对除发送方所有连接对象发送
void fa(int cf)
{
sprintf(sbuf, "%s:%s", mp[cf].c_str(), buf);
for (int cfd : cfds)
{
if (cfd != cf)
{
send(cfd, sbuf, strlen(sbuf), 0);
}
}
printf("发送完毕\n");
}
// 接受链接,并记录链接方名字
void acc()
{
struct sockaddr_in caddr;
int len;
int cfd = accept(sockfd, (struct sockaddr *)&caddr, (socklen_t *)&len);
printf("cfd:%d\n", cfd);
if (cfd == -1)
{
printf("error:%m\n");
exit(0);
}
cfds.insert(cfd);
struct epoll_event e;
e.events = EPOLLIN;
// 操作系统不会修改data中的数据,仅在出现events的事件消息后将数据完整拷贝到目的数组
e.data.fd = cfd;
epoll_ctl(epfd, EPOLL_CTL_ADD, cfd, &e);
int r = recv(cfd, buf, 1024, 0);
buf[r] = 0;
std::string name(buf);
mp[cfd] = name;
std::cout << name << "\n";
}
int main()
{
sockfd = socket(AF_INET, SOCK_STREAM, 0);
printf("sockfd:%d\n", sockfd);
int r;
struct sockaddr_in Saddr;
Saddr.sin_family = AF_INET;
Saddr.sin_port = htons(PORT);
Saddr.sin_addr.s_addr = inet_addr(SIP);
r = bind(sockfd, (struct sockaddr *)&Saddr, sizeof(Saddr));
printf("bind:%d\n", r);
if (r == -1)
{
printf("%m\n");
exit(0);
}
r = listen(sockfd, 10);
printf("listen:%d\n", r);
epfd = epoll_create(1);
printf("epfd:%d\n", epfd);
struct epoll_event ev;
ev.events = EPOLLIN;
ev.data.fd = sockfd;
epoll_ctl(epfd, EPOLL_CTL_ADD, sockfd, &ev);
/*
*/
while (1)
{
int r = epoll_wait(epfd, evs, 20, 0);
if (r == -1)
{
printf("error:%m");
exxit(-1);
}
else if (r == 0)
{
continue;
}
else
{
int rr = r;
for (int i = 0; i < rr; i++)
{
if (evs[i].data.fd == sockfd && evs[i].events & EPOLLIN)
{
// 新连接
acc();
}
else
{
// 新消息
r = recv(evs[i].data.fd, buf, 1024, 0);
if (r <= 0)
{
close(evs[i].data.fd);
epoll_ctl(epfd, EPOLL_CTL_DEL, evs[i].data.fd, &ev);
cfds.erase(evs[i].data.fd);
continue;
}
buf[r] = 0;
fa(evs[i].data.fd);
}
}
}
}
return 0;
}