#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include <sys/wait.h>
#include <poll.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <vector>
#include <iostream>
#define ERR_EXIT(m) \
do \
{ \
perror(m); \
exit(EXIT_FAILURE); \
} while(0)
typedef std::vector<struct pollfd> PollFdList; //单向向量类
int main(void)
{
signal(SIGPIPE, SIG_IGN);//表示屏蔽掉这两个信号
signal(SIGCHLD, SIG_IGN);
//int idlefd = open("/dev/null", O_RDONLY | O_CLOEXEC);
int listenfd;
//if ((listenfd = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
if ((listenfd = socket(PF_INET, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, IPPROTO_TCP)) < 0)//非阻塞的套接字
ERR_EXIT("socket");
struct sockaddr_in servaddr;
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(5188);
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
int on = 1;
if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0)
ERR_EXIT("setsockopt");
if (bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
ERR_EXIT("bind");
if (listen(listenfd, SOMAXCONN) < 0)
ERR_EXIT("listen");
struct pollfd pfd; //一个结构体
pfd.fd = listenfd;
pfd.events = POLLIN;//表示数据可读的事件类型
PollFdList pollfds;//实例化一个向量数组
pollfds.push_back(pfd);//在Vector最后添加一个元素
int nready;
struct sockaddr_in peeraddr;
socklen_t peerlen;
int connfd;
while (1)
{
nready = poll(&*pollfds.begin(), pollfds.size(), -1);
if (nready == -1)
{
if (errno == EINTR)//接收到中断信号
continue;
ERR_EXIT("poll");
}
if (nready == 0) // nothing happended 表示超时
continue;
if (pollfds[0].revents & POLLIN) //&与操作 //如果有数据可读事件发生
{
peerlen = sizeof(peeraddr);
connfd = accept4(listenfd, (struct sockaddr*)&peeraddr,&peerlen, SOCK_NONBLOCK | SOCK_CLOEXEC);
//这里是accept4函数不是accept
if (connfd == -1)//发生错误
ERR_EXIT("accept4");
/*
if (connfd == -1)
{
if (errno == EMFILE)
{
close(idlefd);
idlefd = accept(listenfd, NULL, NULL);
close(idlefd);
idlefd = open("/dev/null", O_RDONLY | O_CLOEXEC);
continue;
}
else
ERR_EXIT("accept4");
}
*/
pfd.fd = connfd;//数据传输socket
pfd.events = POLLIN; //在connfd监听POLLIN(数据可读事件)这里是
pfd.revents = 0;
pollfds.push_back(pfd);
--nready;
// 连接成功
std::cout<<"ip="<<inet_ntoa(peeraddr.sin_addr)<<
" port="<<ntohs(peeraddr.sin_port)<<std::endl;
if (nready == 0)
continue;
}
//std::cout<<pollfds.size()<<std::endl;
//std::cout<<nready<<std::endl;
//it=pollfds.begin()+1 这里加1是因为第一个是监听socket,后面的都是数据socket
for (PollFdList::iterator it=pollfds.begin()+1;
it != pollfds.end() && nready >0; ++it)
{
//遍历一遍各个数据socket是否有数据可读
if (it->revents & POLLIN)
{
--nready;
connfd = it->fd;
char buf[1024] = {0};
int ret = read(connfd, buf, 1024);
if (ret == -1)
ERR_EXIT("read");
if (ret == 0)//表示读取完
{
std::cout<<"client close"<<std::endl;
it = pollfds.erase(it);//删除
--it;
close(connfd);
continue;//进入下次循环
}
std::cout<<buf;
write(connfd, buf, strlen(buf));
}
}
}
return 0;
}
Linux下poll编程
最新推荐文章于 2024-08-11 10:37:55 发布