当前位置: 技术问答>linux和unix
对socket使用select(max_fd,&rd_set,&wr_set,&er_set,&timeout);当服务端断开TCP连接,客户端就会崩溃。怎么解决?谢谢
来源: 互联网 发布时间:2015-12-09
本文导语: for(;;) { sleep(5); printf("nconnecting to serverhost"); bzero(&server_addr,sizeof(server_addr)); server_addr.sin_family=AF_INET; server_addr.sin_addr.s_addr = inet_addr(host_name); server_addr.sin_port=htons(server_port); if((socket_fd=socke...
for(;;)
{
sleep(5);
printf("nconnecting to serverhost");
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr = inet_addr(host_name);
server_addr.sin_port=htons(server_port);
if((socket_fd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("nError openning socket");
close(socket_fd);
continue;
}
fcntl(socket_fd, F_SETFL, O_NONBLOCK);//设为非阻塞
if(connect(socket_fd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1)
{
printf("nError connect ...errno = %d ",errno);
sleep(10);
break;
}
else
{
break;
}
}
printf("nConnect OK...");
while(1)
{
max_fd =socket_fd+1;//
FD_ZERO(&rd_set);
FD_ZERO(&wr_set);
FD_ZERO(&er_set);
FD_SET(socket_fd,&rd_set);
FD_SET(socket_fd,&er_set);
timeout.tv_sec=2;
timeout.tv_usec=0;
ret=select(max_fd,&rd_set,&wr_set,&er_set,&timeout);
if (ret
{
sleep(5);
printf("nconnecting to serverhost");
bzero(&server_addr,sizeof(server_addr));
server_addr.sin_family=AF_INET;
server_addr.sin_addr.s_addr = inet_addr(host_name);
server_addr.sin_port=htons(server_port);
if((socket_fd=socket(AF_INET,SOCK_STREAM,0))==-1)
{
printf("nError openning socket");
close(socket_fd);
continue;
}
fcntl(socket_fd, F_SETFL, O_NONBLOCK);//设为非阻塞
if(connect(socket_fd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr))==-1)
{
printf("nError connect ...errno = %d ",errno);
sleep(10);
break;
}
else
{
break;
}
}
printf("nConnect OK...");
while(1)
{
max_fd =socket_fd+1;//
FD_ZERO(&rd_set);
FD_ZERO(&wr_set);
FD_ZERO(&er_set);
FD_SET(socket_fd,&rd_set);
FD_SET(socket_fd,&er_set);
timeout.tv_sec=2;
timeout.tv_usec=0;
ret=select(max_fd,&rd_set,&wr_set,&er_set,&timeout);
if (ret