#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
const int MAX_CONN=5;
using namespace std;
const int PORT=12345;
bool tolkclient(int sock2)
{
char s100;
recv(sock2,s,100,0);
cout<<s<<"\n";
send(sock2,"Hi",3,0);
if(strcmp(s,"quit")==0)
{
return False;
}
return True;
}
bool waitresponse(int sock,double sec)
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(sock,&fds);
timeval tv;
tv.tv_sec=(unsigned long)sec;
tv.tv_usec=(unsigned long)((sec-(unsigned long)sec)*1000000);
return 1==select(sock+1,&fds,0,0,sec<0?0:&tv);
}
int main()
{
int sock=socket(AF_INET,SOCK_STREAM,0);
sockaddr_in a;
a.sin_family=AF_INET;
a.sin_addr.s_addr=INADDR_ANY;
a.sin_port=htons(PORT);
if(0!=bind(sock,(sockaddr*)&a,sizeof(a)))
{
cout<<"exit\n";
return 1;
}
listen(sock,5);
socklen_t len=sizeof(a);
int connMAX_CONN;
int conn_COUNT=0;
while(1)
{
if(conn_COUNT<MAX_CONN&&waitresponse(sock,0))
{
int sock2=accept(sock,(sockaddr*)&a,&len);
connconn_COUNT=sock2;
conn_COUNT++;
}
for(int i=0;i<conn_COUNT;i++)
{
int sock2=conni;
if(waitresponse(sock2,0))
{
if(!tolkclient(sock2))
{
cout<<"client goes out\n";
close(sock2);
conni=connconn_COUNT-1;
conn_COUNT--;
i--;
}
}
}
}
close(sock);
}