1. 流程描述
跟select很类似,注意这儿将client的第0项固定为listen的socket,
for循环要从1开始遍历
2. 代码
-
cong@msi:/work/test/tcpip/13poll/serv$ cat tcpserv.c
-
#include "utils.h"
-
-
int main ( int argc, char *argv[] )
-
{
-
ssize_t n;
-
int i, maxi;
-
int listenfd, connfd, sockfd;
-
int nready;
-
struct pollfd client[OPEN_MAX]; -->只需要分配一个pollfd即可
-
struct sockaddr_in servaddr, cliaddr;
-
char buf[MAXLINE];
-
socklen_t clilen;
-
listenfd = socket(AF_INET, SOCK_STREAM, 0);
-
if(listenfd< 0)
-
return -1;
-
bzero(&servaddr, sizeof(servaddr));
-
servaddr.sin_family = AF_INET;
-
servaddr.sin_port = htons(13999);
-
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
-
//inet_pton(AF_INET, TIME_SERV_ADDR, &servaddr.sin_addr);
-
-
bind(listenfd, (const struct sockaddr*)&servaddr, sizeof(servaddr));
-
listen(listenfd, LISTENQ);
-
//把第0项固定为listen的socket,其它的作为client的socket
-
client[0].fd = listenfd;
-
client[0].events = POLLRDNORM;
-
maxi = 0;
-
for(i=1; i<OPEN_MAX; i++)
-
client[i].fd = -1; -->其它的sockfd都设为-1
-
while(1)
-
{
-
nready = poll(client, maxi+1, INFTIM);
-
if(nready<0)
-
continue;
-
if(client[0].revents & POLLRDNORM) -->当有变化时先检查固定的listen的socket是否有变化
-
{ -->若有变化,说明client有连接
-
clilen = sizeof(cliaddr);
-
connfd = accept(listenfd, (struct sockaddr*)&cliaddr,&clilen);
-
for(i=0; i<OPEN_MAX; i++)
-
{
-
if(client[i].fd < 0)
-
{
-
client[i].fd = connfd;
-
break;
-
}
-
}
-
if(i==OPEN_MAX)
-
dbmsg("too many clients");
-
client[i].events = POLLRDNORM;
-
if(i>maxi)
-
maxi = i;
-
if(--nready <= 0)
-
continue;
-
}
-
for(i=1; i<=maxi; i++) -->第0个socket固定为listen,所以从第1个socket开始遍历
-
{ -->若有变化,说明client有数据
-
if( (sockfd = client[i].fd) < 0)
-
continue;
-
//if(FD_ISSET(sockfd, &rset))
-
if(client[i].revents & (POLLRDNORM|POLLERR))
-
{
-
if( (n=read(sockfd, buf, MAXLINE)) < 0) -->当收到client的数据<0时
-
{
-
if(errno == ECONNRESET) -->如果是ECONNRESET,则说明client退出
-
{
-
close(sockfd);
-
client[i].fd = -1;
-
}
-
}else {
-
write(sockfd, buf, n);
-
}
-
if(--nready <= 0)
-
break;
-
}
-
}
-
}
-
return EXIT_SUCCESS;
-
}
serv.rar (下载后改名为serv.tar.gz)
client.rar (下载后改名为client.tar.gz)
阅读(929) | 评论(0) | 转发(0) |