socket Server 解決TIME_WAIT狀態等待問題
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
int server()
{
int iSockfd = socket(PF_INET,SOCK_STREAM,0); /*1. 準備socket*/
if(iSockfd == -1)
{
perror("socket:");
return 0;
}
/*2. 準備地址*/
struct sockaddr_in addr;
addr.sin_family = PF_INET;
addr.sin_port = htons(17777);
inet_aton("127.0.0.1",&addr.sin_addr);
int flag=1,len=sizeof(int);
//解決端口TIME_WAIT狀態,無法連接
if( setsockopt(iSockfd, SOL_SOCKET, SO_REUSEADDR, &flag, len) == -1)
{
return -1;
}
int iRes = bind(iSockfd, (struct sockaddr*)&addr, sizeof(addr)); /*3.綁定*/
if(iRes == -1)
{
perror("Bind 失敗:");
return -1;
}
iRes = listen(iSockfd, 100); /*4.監聽*/
if(iRes == -1)
{
perror("監聽失敗:");
return -1;
}
int infds;
while(1)
{
/*5.等待客戶端連接*/
struct sockaddr_in fromaddr;
socklen_t len = sizeof(fromaddr);
/*6.和客戶端通信*/
/*6.1接收客戶端數據*/
char buf[100] = {0};
struct timeval timeout;
timeout.tv_sec = 2;
timeout.tv_usec = 0;
fd_set Readyfd;
FD_ZERO(&Readyfd);
FD_SET(iSockfd, &Readyfd);
infds = select(iSockfd+1, &Readyfd, NULL, NULL, &timeout);
if(infds>0)
{
if(FD_ISSET(iSockfd, &Readyfd))
{
int fd = accept(iSockfd, (struct sockaddr*)&fromaddr,(socklen_t *)&len);
if(-1 == fd)
{
/*告警信息 不影響下一個資源申請 所以一直是監聽狀態*/
continue;
}
if(read(fd, buf, 100)<=0)
{
printf("-----Error\n");
close(fd);
continue;
}
else
{
printf("------buf=%s\n",buf);
//sleep(5);//write(fd,(char *) "Server send date", 100);
sleep(5);
if(write(fd,(char *) "Server send date", 100)<=0)
{
close(fd);
continue;
}
}
}
}
else if(infds < 0)
{
perror("錯誤");
break;
}
else
{
printf("超時處理\n");
//write(iSockfd+1,(char *) "---Server--- Send", 100);
continue;
}
}
close(iSockfd);
return 0;
}
int main()
{
server();
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.