IO多路复用select模型
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
int main()
{
int lfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serv;
serv.sin_family = AF_INET;
serv.sin_port = htons(8888);
serv.sin_addr.s_addr = INADDR_ANY;
bind(lfd, (struct sockaddr*)&serv, sizeof(serv));
listen(lfd, 128);
fd_set readfds;
fd_set tmpfds;
FD_ZERO(&readfds);
FD_ZERO(&tmpfds);
FD_SET(lfd, &readfds);
int nready, cfd, sockfd, i, n;
int maxfd = lfd;
char buf[1024];
while (1) {
tmpfds = readfds;
int nready = select(maxfd + 1, &tmpfds, NULL, NULL, NULL);
if (nready < 0) {
printf("errrno\n");
return -1;
}
if (FD_ISSET(lfd, &tmpfds)) {
cfd = accept(lfd, NULL, NULL);
FD_SET(cfd, &readfds);
if (maxfd < cfd) {
maxfd = cfd;
}
if (--nready == 0) {
continue;
}
}
for (i = lfd + 1; i < maxfd + 1; i++) {
sockfd = i;
if (FD_ISSET(sockfd, &tmpfds)) {
memset(buf, 0*00, sizeof(buf));
n = read(sockfd, buf, sizeof(buf));
if (n <= 0) {
printf("%dduankai\n", sockfd);
close(sockfd);
FD_CLR(sockfd, &readfds);
continue;
}
else {
printf("%dclient:%s\n", sockfd, buf);
write(sockfd, buf, strlen(buf));
}
if (--nready == 0) {
break;
}
}
}
}
close(lfd);
return 0;
}