|
![](static/image/common/ico_lz.png)
楼主 |
发表于 2010-5-13 15:49:16
|
显示全部楼层
大家帮忙看看我的select程序有无问题:
#include <lwip/sockets.h> /* 使用BSD Socket接口必须包含sockets.h这个头文件*/
#define MYPORT 4000 //port we're listening on
int tcpserv(void)
{
fd_set master; //master file descriptor list
fd_set read_fds; //temp file descriptor list for select()
struct sockaddr_in myaddr; //server address
struct sockaddr_in remoteaddr; //client address
int fdmax; //maximum file descriptor number
int listener; //listening socket descriptor
int newfd; //newly accept()ed socket descriptor
char bufrecv[32];
char bufsend[512];
int nbytes;
int opt; //for setsocket()
int addrlen;
int i,j;
for(j = 0;j < 512; j++) {
bufsend[j] = 't';
}
FD_ZERO(&master); //clear the master and temp sets
FD_ZERO(&read_fds);
//get the listener
listener = socket(AF_INET, SOCK_STREAM, 0);
//set the socket
setsockopt(listener, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(int));
//bind
myaddr.sin_family = AF_INET;
myaddr.sin_addr.s_addr = INADDR_ANY;
myaddr.sin_port = htons(MYPORT);
memset(&(myaddr.sin_zero), '\0', 8);
bind(listener, (struct sockaddr *)&myaddr, sizeof(myaddr));
//listen
listen(listener, 10);
//add the listener to the master set
FD_SET(listener, &master);
//keep track of the biggest file descriptor
fdmax = listener; //so far, it's this one
//main loop
for( ; ; ) {
read_fds = master; //copy it
select(fdmax+1, &read_fds, NULL, NULL, NULL);
//run through the existing connections looking for data to read
for(i = 0; i <= fdmax; i++) {
if(FD_ISSET(i, &read_fds)) { //we got one!!
if(i == listener) {
//handler new connections
addrlen = sizeof(remoteaddr);
if((newfd = accept(listener, (struct sockaddr *)&remoteaddr, &addrlen)) == -1) {
} else {
FD_SET(newfd, &master); //add to master set
if(newfd > fdmax) { //keep track of the maximum
fdmax = newfd;
}
}
} else {
//handle data from a client
nbytes = recv(i, bufrecv, sizeof(bufrecv), 0);
if(nbytes <= 0) {
//got error or connection closed by client
closesocket(i); //bye!
FD_CLR(i, &master); //remove from master set
} else {
//send to client
send(i, bufsend, sizeof(bufsend), 0);
}
}
}
}
}
return 0;
} |
|