- 论坛徽章:
- 0
|
10可用积分
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <time.h>
#include <sys/times.h>
#include <sys/select.h>
void init_addr(struct sockaddr_in *addr);
int main()
{
int sockfd, clilen, listenfd, connfd;
int n, i, maxfd, maxi, nready, client[FD_SETSIZE];
fd_set rset, allset;
struct sockaddr_in addr, cliaddr;
char str[20];
if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
fprintf(stderr, "socket error");
exit(-1);
}
init_addr(&addr);
if(bind(listenfd, (struct sockaddr *)&addr, sizeof(addr)) < 0){
fprintf(stderr, "bind error");
exit(-1);
}
listen(listenfd, 100);
FD_ZERO(&allset);
FD_SET(listenfd, &allset);
maxfd = listenfd;
for(i = 0; i < FD_SETSIZE; i++)
client = -1;
maxi = -1;
while(1){
rset = allset;
nready = select(maxfd + 1, &rset, NULL, NULL, NULL);
fprintf(stderr, "%d", nready);
fprintf(stderr, "%d", FD_ISSET(listenfd, &rset));
if(FD_ISSET(listenfd, &rset)) {
clilen = sizeof(cliaddr);
connfd = accept(listenfd, (struct sockaddr *)&cliaddr,
&clilen);
for(i = 0; i < FD_SETSIZE; i++)
if(client < 0) {
client = connfd;
break;}
FD_SET(connfd, &allset);
if(connfd > maxfd)
maxfd = connfd;
if(i > maxi)
maxi = i;
if(--nready <= 0)
continue;
}
for(i = 0; i < maxi; i++) {
if((sockfd = client) < 0)
continue;
if(FD_ISSET(sockfd, &rset)) {
if(n = recv(sockfd,str,sizeof(str), 0) == 0)
{
close(sockfd);
FD_CLR(sockfd, &allset);
client = -1;
}
else {
send(sockfd, "def", sizeof("def"), 0);
}
if(--nready <= 0)
break;
}
}
}
}
在程序中我加入了fprintf(stderr, "%d", nready);fprintf(stderr, "%d", FD_ISSET(listenfd, &rset));来验证,nready的值是1,表明有一个连接,但是FD_ISSET(listenfd, &rset)的值却是0,导致程序进入死循环,整个屏幕显示的都是10101010**********,FD_ISSET(listenfd, &rset)的值怎么会是0???
[ 本帖最后由 cinuxer 于 2007-7-29 15:59 编辑 ] |
|