关于epoll的介绍此处不赘述,可以参考这篇博文 linux epoll详解及使用方法概述
这里给出一个epoll实现的聊天室程序,实现群聊功能,分为server端和client端代码:
server.cpp:
//server.cpp
#include <iostream>
#include <list>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/epoll.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;
//选用list存放sockfd
list<int> clients_list;
//server port
#define SERVER_PORT 8888
//epoll支持的最大并发量
#define EPOLL_SIZE 5000
//message buf size
#define BUF_SIZE 0xFFFF
#define SERVER_WELCOME "Welcome you join to the chat room! Your chat ID is: Client #%d"
#define SERVER_MESSAGE "ClientID %d say >> %s"
// exit
#define EXIT "EXIT"
#define CAUTION "There is only one int the char room!"
int setnonblocking(int sockfd){
fcntl(sockfd, F_SETFL, fcntl(sockfd, F_GETFD, 0) | O_NONBLOCK);
return 0;
}
void addfd(int epollfd, int fd, bool enable_et){
struct epoll_event ev;
ev.data.fd = fd;
ev.events = EPOLLIN;
if(enable_et){
ev.events = EPOLLIN | EPOLLET;
}
epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev);
setnonblocking(fd);
}
int sendBroadcastmessage(int clientfd){
char buf[BUF_SIZE], message[BUF_SIZE];
//清零
bzero(buf, BUF_SIZE);
bzero(message, BUF_SIZE);
printf("read from client(clientID = %d)\n", clientfd);
int len = recv(clientfd, buf, BUF_SIZE, 0);
//len=0 client关闭了连接
if(len == 0){
close(clientfd);
clients_list.remove(clientfd);
printf("ClientID = %d closed.\n now there are %d client in the char room\n", clientfd, (int)clients_list.size());
}else{//进行广播
if(clients_list.size() == 1){
send(clientfd, CAUTION, strlen(CAUTION), 0);
return len;
}
sprintf(message, SERVER_MESSAGE, clientfd, buf);
list<int>::iterator iter;
for(iter = clients_list.begin(); iter != clients_list.end(); ite