This must be supported, and who told him to advertise that select is a standard.
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/time.h>
#include <unistd.h>
int main (int argc, char *argv[])
{
int LISTENFD, CONNFD;
struct sockaddr_in serveraddr;
Char buff[20];
if ((LISTENFD = socket (af_inet, sock_stream, 0)) = = 1)
{
printf ("Create Error:%s (errno=%d) \ n", Strerror (errno), errno);
Exit (0);
}
memset (&serveraddr, 0, sizeof (SERVERADDR));
serveraddr.sin_family = af_inet;
SERVERADDR.SIN_ADDR.S_ADDR = htonl (Inaddr_any);
Serveraddr.sin_port = htons (6789);
if (Bind (LISTENFD, (struct sockaddr*) &serveraddr, sizeof (serveraddr)) = = 1)
{
printf ("Bind error:%s (errno=%d) \ n", Strerror (errno), errno);
exit (0);
}
if (Listen (LISTENFD, 5) = = 1)
{
printf ("Listen Error:%s (errno=%d) \ n ", Strerror (errno), errno);
exit (0);
}
if (fcntl (LISTENFD, F_SETFL, o_nonblock) = = 1)
{
printf ("Fcntl Error:%s (errno=%d) \ n ", Strerror (errno), errno);
exit (0);
}
struct Timeval timeout;
timeout.tv_sec = 60;
timeout.tv_usec = 0;
int ret, i = 0;
int maxfd;//= LISTENFD;
int Fds[6] = {0,0,0,0,0,0,0};
fd_set readfd, ALLFD;
Fd_zero (&READFD);
Fd_set (LISTENFD, &ALLFD);
MAXFD = LISTENFD;
fds[i++] = LISTENFD;
while (1)
{
READFD = ALLFD;
ret = SELECT (Maxfd + 1, &READFD, NULL, NULL,/*&timeout*/0);
if (ret = 1)
{
printf ("Select Error:%s (errno=%d) \ n", Strerror (errno), errno);
Exit (0);
}
else if (ret = 0)
{
printf ("Select Timeout Error:%s (errno=%d) \ n", Strerror (errno), errno);
Exit (0);
}
Else
{
if (Fd_isset (LISTENFD, &READFD))
{
int CONNFD = Accept (LISTENFD, (struct sockaddr*) null, NULL);
if (CONNFD = = 1)
{
printf ("Accept Error:%s (errno=%d) \ n", Strerror (errno), errno);
}
Else
{
if (i > 5)
{
printf ("Max Connect num, close it\n");
Close (CONNFD);
Continue
Exit (0);
}
printf ("Accept new socket\n");
if (Fcntl (CONNFD, F_SETFL, o_nonblock) = = 1)
{
printf ("fcntl error:connfd =%d,%s (errno=%d) \ n", CONNFD, Strerror (errno), errno);
Exit (0);
}
Fd_set (CONNFD, &ALLFD);
if (Maxfd < CONNFD)
MAXFD = CONNFD;
fds[i++] = CONNFD;
}
}
Else
{
int k;
for (k = 1; k < 6; k++)
{
printf ("Loop k =%d\n", k);
if (Fd_isset (Fds[k], &READFD))
{
int len = recv (fds[k], buff, 20, 0);
if (len = = 1)
{
printf ("recv error:connfd =%d,%s (errno=%d) \ n", Connfd,strerror (errno), errno);
Exit (0);
}
else if (len = = 0)
{
FD_CLR (Fds[k], &ALLFD);
printf ("Socket close\n");
Close (Fds[k]);
Fds[k] = 0;
}
Else
{
Buff[len] = ' the ';
printf ("recv data =%s, Len =%d\n", buff, Len);
memset (Buff, 0, 20);
}
}
}
}
printf ("One More time.\n");
}
}
for (i = 0; i < 7; i++)
{
if (Fds[i]!= 0)
Close (Fds[i]);
}
return 0;
}
The client end root is the same as the previous ones.
All said select all kinds of bad, in fact summed up as if on 2 points:
1. The total number of controls is limited
2. Traversal rotation inefficient
Poll better than he is the 1th, in fact, the two in actual use may be similar.