使用select完成TCP并发服务器
- #include "myhead.h"
- #define ERR_MSG(msg) do{\
- printf("%d\n",__LINE__);\
- perror(msg);\
- }while(0)
- #define PORT 3696
- #define IP "192.1168.10.22"
- int main(int argc, const char *argv[])
- {
- //套接字
- int sfd=socket(AF_INET,SOCK_STREAM,0);
- if(sfd==-1)
- {
- ERR_MSG("socket");
- return -1;
- }
- //允许端口复用
- int reuse=1;
- if(setsockopt(sfd,SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse))<0)
- {
- ERR_MSG("setsockopt");
- return -1;
- }
- //绑定服务器
- struct sockaddr_in sin;
- sin.sin_family=AF_INET;
- sin.sin_port=htons(PORT);
- sin.sin_addr.s_addr=inet_addr(IP);
- if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin))==-1)
- {
- ERR_MSG("bind");
- return -1;
- }
- //设置监听状态
- if(listen(sfd,128)==-1)
- {
- ERR_MSG("listen");
- return -1;
- }
- fd_set readfds,tempfds;
- //清空
- FD_ZERO(&readfds);
- //文件描述符
- FD_SET(0,&readfds);
- FD_SET(sfd,&readfds);
- struct sockaddr_in cin;
- socklen_t addrlen=sizeof(cin);
- int newfd=-1;
- char buf[32];
- ssize_t res=0;
- int s_res=-1;
- int maxfd=sfd;
- int sndfd=-1;
- struct sockaddr_in save[1024];
- while(1)
- {
- tempfds =readfds;
- maxfd=maxfd>newfd?maxfd:newfd;
- s_res=select(maxfd+1,&tempfds,NULL,NULL,NULL);
- if(s_res == -1){
- ERR_MSG("select");
- return -1;
- }else if(s_res == 0){
- printf("time out\n");
- break;
- }
- for(int i = 0;i <= maxfd;i++){
- if(FD_ISSET(i,&tempfds) == 0)
- continue;
- if(0 == i){
- printf("触发键盘输入事件\n");
- bzero(buf,sizeof(buf));
- int ret = scanf("%d %s",&sndfd,buf);
- if(ret != 2){
- printf("您的输入格式有误:sndfd buf\n");
- return -1;
- }
- if(sndfd <= 2 || FD_ISSET(sndfd,&readfds) == 0){
- printf("您输入的文件描述符不合法 snfd = %d\n",sndfd);
- return -1;
- }
- //发送
- if(send(sndfd,buf,sizeof(buf),0) == -1){
- ERR_MSG("send");
- return -1;
- }
- printf("send success!\n");
-
- }else if(sfd == i){
- printf("触发客户端连接事件\n");
- //获取一个已经完成的客户端信息,生成一个新的文件描述符 accept
- newfd = accept(sfd,(struct sockaddr*)&cin,&addrlen);
- if(newfd == -1){
- ERR_MSG("accept");
- return -1;
- }
- printf("[%s:%d]客户端链接成功! newfd = %d\n",inet_ntoa(cin.sin_addr),ntohs(cin.sin_port),newfd);
- save[newfd] = cin;
- FD_SET(newfd,&readfds);
-
- }else{
- printf("触发接收客户端数据事件\n");
- //接收
- bzero(buf,sizeof(buf));
- res = recv(i,buf,sizeof(buf),0);
- if(res == -1){
- ERR_MSG("recv");
- return -1;
- }else if(res == 0){
- printf("[%s:%d]客户端已下线! newfd = %d\n",inet_ntoa(save[i].sin_addr),ntohs(save[i].sin_port),i);
- close(i);
- FD_CLR(i,&readfds);
- while(FD_ISSET(maxfd,&readfds) == 0 && maxfd-->=0);
- continue;
- }
- printf("[%s:%d] newfd = %d buf = %s \n",inet_ntoa(save[i].sin_addr),ntohs(save[i].sin_port),i,buf);
-
- //发送
- if(send(i,buf,sizeof(buf),0) == -1){
- ERR_MSG("send");
- return -1;
- }
- printf("send success!\n");
- }
- }
- }
- //关闭文件描述符
- if(close(sfd)<0){
- ERR_MSG("close");
- return -1;
- }
- if(close(newfd) < 0){
- ERR_MSG("close");
- return -1;
- }
-
- return 0;
- }