使用多路复用实现一个服务器与多个客户端的通信:代码范例: 服务器: #include<stdio.h> #include<netinet/in.h> #include<stdlib.h> #include<string.h> #include <sys/types.h> #include <sys/socket.h> #include<pthread.h> #include<strings.h> void send1(int *a) { int i; char buf[20]; bzero(buf,20); fgets(buf,20,stdin); for(i=0;i<12;i++) { if(a[i] !=0) send(a[i],buf,20,0); } } int main() { int fds[12]={0}; int maxfd = -1; int socketfd = socket(PF_INET,SOCK_STREAM,0); if(socketfd>maxfd) maxfd = socketfd; struct sockaddr_in saddr; memset(&saddr,0,sizeof(saddr)); saddr.sin_family = PF_INET; saddr.sin_port = htons(6000); saddr.sin_addr.s_addr = inet_addr("192.168.1.46"); int newsocketfd; int n = 1; setsockopt(socketfd, SOL_SOCKET, SO_REUSEADDR, &n, sizeof(int)); if(bind(socketfd,(struct sockaddr*)&saddr,sizeof(struct sockaddr_in))<0) perror("bind() error!\n"); if(listen(socketfd,5)<0) perror("listen() error!\n"); struct sockaddr_in caddr; int s = sizeof(struct sockaddr); // newsocketfd = accept(socketfd,(struct sockaddr*)&caddr,&s); fd_set fd; FD_ZERO(&fd); int ret; char buf[20],buf1[20]; int i; int rsize; while(1) { FD_ZERO(&fd); FD_SET(0,&fd); FD_SET(socketfd,&fd); for(i=0;i<12;i++) { // printf("--------------\n"); if(fds[i]!=0) FD_SET(fds[i],&fd); } ret = select(maxfd+1,&fd,NULL,NULL,NULL); if(ret<0) { perror("select() error!\n"); break; } else if(ret ==0) { continue; } else { if(FD_ISSET(socketfd,&fd)) { newsocketfd = accept(socketfd,(struct sockaddr*)&caddr,&s); if(newsocketfd>maxfd) { // printf("--------------\n"); maxfd = newsocketfd; for(i=0;i<12;i++) { if(fds[i]==0) { fds[i] = newsocketfd; break; } } } continue; } // printf("helo\n"); for(i=0;i<12;i++) { if(fds[i] !=0 && FD_ISSET(fds[i],&fd)) { bzero(buf1,20); if(recv(fds[i],buf1,20,0)==0) { close(fds[i]); fds[i] = 0; } printf("%s",buf1); } } if(FD_ISSET(0,&fd)) { send1(fds); } } } close(socketfd); close(newsocketfd); } 客户端: #include<stdio.h> #include<pthread.h> #include<netinet/in.h> #include<stdlib.h> #include<string.h> #include<strings.h> #include<sys/types.h> #include<sys/socket.h> int main() { int socketfd,ret; fd_set fd; FD_ZERO(&fd); FD_SET(0,&fd); socketfd = socket(PF_INET,SOCK_STREAM,0); FD_SET(socketfd,&fd); ret = select(socketfd+1,&fd,NULL,NULL,NULL); struct sockaddr_in saddr; memset(&saddr,0,sizeof(saddr)); saddr.sin_family = PF_INET; saddr.sin_port = htons(6000); saddr.sin_addr.s_addr = inet_addr("192.168.1.46"); if(connect(socketfd,(struct sockaddr *)&saddr,sizeof(struct sockaddr))<0) perror("connect() error!\n"); // pthread_t pthreadid; // pthread_create(&pthreadid,NULL,func,NULL); char buf[20],buf1[20]; while(1) { bzero(buf,20); bzero(buf1,20); FD_SET(0,&fd); FD_SET(socketfd,&fd); ret = select(socketfd+1,&fd,NULL,NULL,NULL); if(FD_ISSET(socketfd,&fd)) { if(recv(socketfd,buf1,sizeof(buf1),0)<0) perror("recv() error!\n"); printf("%s",buf1); continue; } if(FD_ISSET(0,&fd)) { fgets(buf,20,stdin); if(send(socketfd,buf,strlen(buf),0)<0) perror("send() error!\n"); continue; } }
时间: 2024-10-18 09:43:27