/* NAME: select0 SYNOPSIS: select0 DESCRIPTION: The program waits until two clients are connected then And only them its serve both clients by echoing to each Whatever it sends. The programs exits when BOTH clients are done. The select statement "blocks 1 second" until one socket has activity */ #include "def" main() { fd_set read_template; struct timeval wait; struct sockaddr_in server; char buf[102]; int Sock, length, Sock1,Sock2, nb, Sock1IsActive,Sock2IsActive; /* create the accepting socket */ Sock = socket (PF_INET,SOCK_STREAM,0); if ( Sock < 0 ) { perror("opening stream Socket"); exit(0); } /** bind Socket using wildcards and any available port */ server.sin_family = AF_INET; server.sin_addr.s_addr = INADDR_ANY; server.sin_port = 0; if ( bind (Sock, (SA *)&server, sizeof(server)) ) { perror("binding stream Socket"); } /** Find out assigned port number and print it out */ length = sizeof(server); if ( getsockname (Sock,(SA *)&server,&length) ) { perror("getting Socket name"); exit(0); } printf("Socket has port #%d\n", ntohs(server.sin_port)); printf("...waiting for connection ...\n"); /** Start accepting connections */ listen (Sock, 5); Sock1= accept(Sock,0,0); Sock1IsActive=1; printf("connected to first client\n"); Sock2 = accept(Sock,0,0); Sock2IsActive=1; printf("connected to second client\n"); wait.tv_sec = 1; wait.tv_usec = 0; do { FD_ZERO(&read_template); if (Sock1IsActive) FD_SET(Sock1,&read_template); if (Sock2IsActive) FD_SET(Sock2,&read_template); nb = select(FD_SETSIZE, &read_template, (fd_set *) 0, (fd_set *) 0,&wait); if (nb <0) { perror("Error in select"); exit(1); } if (nb != 0) { /* 0 time out */ if(FD_ISSET(Sock1, &read_template)){ EchoServe(Sock1, &Sock1IsActive); } if(FD_ISSET(Sock2, &read_template)){ EchoServe(Sock2, &Sock2IsActive); } } } while ( Sock1IsActive || Sock2IsActive ); printf("Both clients are done ...exiting...\n"); close(Sock1); close(Sock2); exit(0); } EchoServe(Psock, SockIsActive) int Psock, *SockIsActive; { char buf[512]; int rc; /** get data from client and echo it back */ if( (rc=recv(Psock, buf, sizeof (buf), 0)) < 0) perror("receiving stream message"); if (rc > 0){ buf[rc]=NULL; printf("Received: %s\n", buf); if (send(Psock, buf, rc, 0) <0 ) perror("sending stream message"); } else { printf("Disconnected..\n"); close (Psock); *SockIsActive=0; } }