#include <stdlib.h>
#include <dirent.h>
#include <time.h>
#include <unistd.h>
#include <dirent.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <error.h>
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;
}
转载于:https://blog.51cto.com/ayang/1653408