/* NAME: select1 SYNOPSIS: select1 DESCRIPTION: The program waits until one client is connected then serve that client and when the second client is connected it serve both clients. The service is an echo service. The programs exits when BOTH clients are done. The select statement "blocks forever" 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, NumClients, 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 */ NumClients = 0; listen (Sock, 5); Sock1= accept(Sock,0,0); Sock1IsActive=1; NumClients = 1; printf("connected to first client\n"); do { FD_ZERO(&read_template); if (NumClients < 2) FD_SET(Sock,&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, NULL); if (nb <0) { perror("Error in select"); exit(1); } if (FD_ISSET(Sock, &read_template)){ Sock2 = accept(Sock,0,0); Sock2IsActive=1; printf("connected to second client\n"); NumClients=2; } 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; } }