单线程轮询程序
主页 上一层 设计的要点 程序结构 简单的FTP Server 单线程轮询程序 网络仿真设备

 

select函数的解释

 

程序段节选:

int listenfd, connfd, maxfd=0;

int nready;

fd_set rset, allset;

struct sockaddr_in cliaddr, servaddr;

int clilen;

 

listenfd = socket(AF_INET, SOCK_STREAM, 0);

if (listenfd > maxfd) maxfd = listenfd;

 

memset(&servaddr, 0, sizeof(servaddr));

servaddr.sin_family = AF_INET;

servaddr.sin_addr.s_addr = htonl(INADDR_ANY);

servaddr.sin_port = htons(4321);

 

bind(listenfd, (struct sockaddr *) &servaddr, sizeof(servaddr));

 

FD_ZERO(&allset);

FD_SET(listenfd, &allset);

listen(listenfd, 10);

 

/* main loop */

while (1) {

rset = allset;

nready = select(maxfd+1, &rset, NULL, NULL, NULL);

 

if (FD_ISSET(listenfd, &rset)) {

/* 有新的客户端连接请求

clilen = sizeof(cliaddr);

connfd = accept(listenfd, (struct sockaddr*)&cliaddr,&clilen);

if (client_num == FD_SETSIZE) {

fprintf(stderr, "too many clients\n");

exit(-1);

}

FD_SET(connfd, &allset);

if (connfd > maxfd) maxfd = connfd;

if (--nready <= 0) continue;

}

 

//以下依次判断FD_ISSET(某个socket, &rset) 并做相应处理

}