int fd, max_fd, tmp_fd;
int fd_array[FD_NUM];
int i, rc;
buffer buf[BUF_SIZE];
fd_set read_fd, all_fd;
struct sockaddr_in local;
local.sin_family = AF_INET;
local.sin_addr.s_addr = htonl(INADDR_ANY);
local.sin_port = htons(PORT);
if((fd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
{
//error
}
if(bind(fd, (struct sockaddr*)&local, sizeof(local)) == -1)
{
//error
}
if(listen(fd, MAX_CONNECTION) == -1)
{
//error
}
memset(fd_array, -1, FD_NUM);
fd_array[0] = fd;
FD_ZERO(&all_fd);
FD_SET(fd, &all_fd);
max_fd = fd;
while(1)
{
read_fd = all_fd;
if(select(max_fd + 1, &read_fd, NULL, NULL, NULL) == -1)
{
continue;
}
if(FD_ISSET(fd, &readfd))
{
if((tmp_fd = accept(fd, NULL, NULL)) == -1)
{
continue;
}
else
{
for(i = 0; i < FD_NUM; i++)
{
if(fd_array[i] == -1)
{
fd_array[i] = tmp_fd;
}
}
FD_SET(tmp_fd, &allfd);
if(tmp_fd > max_fd)
{
max_fd = tmp_fd;
}
}
continue;
}
for(i = 0; i < FD_NUM; i++)
{
if(FD_ISSET(fd_array[i]), &read_fd)
{
rc = recv(fd_array[i], buf, BUF_SIZE, 0);
if(rc <= 0)
{
//error
}
else
{
buf[rc] = '\0';
//your operation
}
break;
}
}
}
本文地址:http://com.8s8s.com/it/it33304.htm