select实现的TCP并发服务器
#include <myhead.h>
#define SER_PORT 8888
#define SER_IP "192.168.117.96"
int main(int argc, const char *argv[])
{
int sfd = -1;
sfd = socket(AF_INET,SOCK_STREAM,0);
if(sfd == -1)
{
perror("socket");
return -1;
}
printf("sfd = %d\n",sfd);
int reuse = 1;
if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse)) == -1)
{
perror("setsockopt");
return -1;
}
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_port = htons(SER_PORT);
sin.sin_addr.s_addr = inet_addr(SER_IP);
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin)) == -1)
{
perror("bind");
return -1;
}
printf("bind success\n");
if(listen(sfd,128) == -1)
{
perror("listen");
return -1;
}
printf("listen success\n");
int newfd = -1;
struct sockaddr_in cin;
socklen_t addrlen = sizeof(cin);
char sbuf[128] = {0};
fd_set readfds,tempfds;
FD_ZERO(&readfds);
FD_SET(0,&readfds);
FD_SET(sfd,&readfds);
int maxfd = sfd;
struct sockaddr_in cin_arr[1024];
while(1)
{
tempfds = readfds;
int res = select(maxfd+1,&tempfds,NULL,NULL,NULL);
if(res == -1)
{
perror("select");
return -1;
}
else if(res == 0)
{
printf("time out\n");
return -1;
}
for(int i = 0;i<=maxfd;i++)
{
if(!FD_ISSET(i,&tempfds))
{
continue;
}
if(i == sfd)
{
if((newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen)) == -1)
{
perror("accept");
return -1;
}
printf("[%s %d]:发来连接请求\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port));
cin_arr[newfd] = cin;
FD_SET(newfd,&readfds);
if(newfd > maxfd)
{
maxfd = newfd;
}
}
else if(i == 0)
{
fgets(sbuf,sizeof(sbuf),stdin);
sbuf[strlen(sbuf)-1] = 0;
printf("触发了键盘输入事件:%s\n",sbuf);
for(int i = 4;i<maxfd;i++)
{
send(i,sbuf,sizeof(sbuf),0);
}
printf("发送成功\n");
}
else
{
char rbuf[128] = {0};
bzero(rbuf,sizeof(rbuf));
int res = recv(i,rbuf,sizeof(rbuf)-1,0);
if(res == 0)
{
printf("客户端已经下线\n");
close(i);
FD_CLR(i,&readfds);
for(int k = maxfd;k >= sfd;k--)
{
if(FD_ISSET(k,&readfds))
{
maxfd = k;
break;
}
}
continue;
}
printf("[%s %d]:%s\n",inet_ntoa(cin_arr[i].sin_addr),ntohs(cin_arr[i].sin_port),rbuf);
strcat(rbuf,">_<");
send(i,rbuf,strlen(rbuf),0);
printf("发送成功\n");
}
}
}
close(sfd);
return 0;
}