#include #include #include #include #include #include #include #include #include #include /* <===== */ extern int errno; #define BUFFER_SIZE 1024 #define MAX_CLIENTS 100 char *msg = "ack"; int main() { char buffer[ BUFFER_SIZE ]; int sock, newsock, len, fromlen, n; fd_set readfds; int client_sockets[ MAX_CLIENTS ]; /* client socket fd list */ int client_socket_index = 0; /* next free spot */ /* socket structures from /usr/include/sys/socket.h */ struct sockaddr_in server; struct sockaddr_in client; unsigned short port = 8127; /* Create the listener socket as TCP socket */ /* (use SOCK_DGRAM for UDP) */ sock = socket( PF_INET, SOCK_STREAM, 0 ); if ( sock < 0 ) { perror( "socket()" ); exit( 1 ); } server.sin_family = PF_INET; server.sin_addr.s_addr = INADDR_ANY; /* htons() is host-to-network-short for marshalling */ /* Internet is "big endian"; Intel is "little endian" */ server.sin_port = htons( port ); len = sizeof( server ); if ( bind( sock, (struct sockaddr *)&server, len ) < 0 ) { perror( "bind()" ); exit( 1 ); } fromlen = sizeof( client ); listen( sock, 5 ); /* 5 is number of backlogged waiting clients */ printf( "Listener socket created and bound to port %d\n", port ); while ( 1 ) { int q; struct timeval timeout; timeout.tv_sec = 3; timeout.tv_usec = 400; /* PLUS 400 msec */ /* Set timeout values to 0 for a non-blocking "poll" */ FD_ZERO( &readfds ); FD_SET( sock, &readfds ); printf( "Set FD_SET to include listener fd %d\n", sock ); for ( q = 0 ; q < client_socket_index ; q++ ) { FD_SET( client_sockets[ q ], &readfds ); printf( "Set FD_SET to include client socket fd %d\n", client_sockets[ q ] ); } q = select( FD_SETSIZE, &readfds, NULL, NULL, &timeout ); /* q is the number of ready file descriptors */ if ( q == 0 ) { printf( "Timeout. Do something else....\n" ); } if ( FD_ISSET( sock, &readfds ) ) { newsock = accept( sock, (struct sockaddr *)&client, &fromlen ); printf( "Accepted client connection\n" ); client_sockets[ client_socket_index++ ] = newsock; } for ( q = 0 ; q < client_socket_index ; q++ ) { int fd = client_sockets[ q ]; if ( FD_ISSET( fd, &readfds ) ) { n = recv( fd, buffer, BUFFER_SIZE - 1, 0 ); if ( n == 0 ) { int k; printf( "Client on fd %d closed connection\n", fd ); /* remove fd from client_sockets[] array: */ for ( k = 0 ; k < client_socket_index ; k++ ) { if ( fd == client_sockets[ k ] ) { /* found it -- copy remaining elements over fd */ int m; for ( m = k ; m < client_socket_index - 1 ; m++ ) { client_sockets[ m ] = client_sockets[ m + 1 ]; } client_socket_index--; break; /* all done */ } } } else if ( n < 0 ) { perror( "recv()" ); } else { buffer[n] = '\0'; printf( "Received message from fd %d: %s\n", fd, buffer ); n = send( fd, msg, strlen( msg ), 0 ); if ( n < strlen( msg ) ) { perror( "send()" ); } } } } } return 0; /* we never get here */ }