修改之前的多路复用程序,增加如果连接断开以后主程序的处理。
host.c:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define NUM 5
void main(int argc, char **argv[])
{
int fd, fd1;
int len, i;
struct sockaddr_in add;
struct fd_set fds;
struct timeval timeout;
char msg[100];
int Cfd[NUM];
int count = 0;
int code;
timeout.tv_sec = 2;
timeout.tv_usec = 0;
len = sizeof(add);
bzero(&add, len);
add.sin_family=AF_INET;
add.sin_port=htons(10000);
add.sin_addr.s_addr=htonl(INADDR_ANY);
fd = socket(AF_INET, SOCK_STREAM, 0);
if(fd < 0) printf("socket err\n");
bind(fd, (struct sockaddr *)&add, len);
listen(fd, SOCK_STREAM);
while(1){
fd1 = accept(fd, (struct sockaddr *)&add, &len);
if(fd1>0) {
Cfd[count++]=fd1;
printf("accept %d \n", count);
if(count == NUM) break;
}
sleep(1);
}
printf("end accept\n");
while(1){
printf("now circlie\n");
FD_ZERO(&fds);
fd1 = 0;
for(i=0;i if(Cfd[i]==0) continue;
FD_SET(Cfd[i],&fds);
if(fd1< Cfd[i])fd1 = Cfd[i];
}
if(fd1 == 0) {
printf("all connect closed\n");
break;
}
fd1 = fd1+1;
code = select(fd1, &fds, NULL, NULL, &timeout);
printf("select:%d\n", code);
if(code > 0){
for(i=0;i if(FD_ISSET(Cfd[i], &fds)&&Cfd[i]!=0){
memset(msg, 0,sizeof(msg));
code = recv(Cfd[i], msg, 100, 0);
if(code <= 0) {
printf("%d connect closed\n", i);
Cfd[i] = 0;
}
else printf("%d:recv %s\n",i,msg);
}
}
}
sleep(1);
}
close(fd);
for(i=0;i}
cli.c:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define NUM 5
void main(int argc, char **argv[])
{
int fd[NUM];
int len, i;
struct sockaddr_in add;
char msg[100];
len = sizeof(add);
bzero(&add, len);
add.sin_family=AF_INET;
add.sin_port=htons(10000);
add.sin_addr.s_addr=inet_addr("10.144.15.234");
for(i=0;i fd[i] = socket(AF_INET, SOCK_STREAM, 0);
if(fd[i]<0) printf("fd%d socket err\n", i);
connect(fd[i], (struct sockaddr *)&add, len);
printf("connect: %d\n", i);
}
printf("connect end\n");
sleep(10);
//上面的延时用于验证select的主机延时阻塞功能
for(i=4;i>-1;i--){
sprintf(msg, "i am %d\n", i);
send(fd[i], msg, strlen(msg), 0);
printf("send :%s\n", msg);
sleep(5);
}
for(i=0;i}
makefile:
LIB = -lsocket -lnsl
all : clean host cli
.PHONY : all
clean :
-rm *.o sem core
cli : cli.o
cc -o cli cli.o $(LIB)
cli.o : cli.c
cc -c cli.c $(LIB)
host : host.o
cc -o host host.o $(LIB)
host.o : host.c
cc -c host.c $(LIB)
阅读(604) | 评论(0) | 转发(0) |