/***************************************************************************** * Example: Chat server using NetLib * Author: Simon Amor * Sets up a VERY simple chat server on your machine * * Copyright: 1994 - Simon Amor ***/ #include #include /* #includes Netlib requires */ #include #include #include #include #include #include #include #include #include /* Netlib include */ #include #define BUFLEN 1024 #define CONNS 10 #define PORT 7777 /* Define a simple macro for socket checking */ #define CheckActive(x,f) FD_ISSET(x,f) /* array of file descriptors - 0=not used */ int fd_array[CONNS]; /* flag for whether the server is shutting down or not, YES=1 */ int server_down; /***************************************************************************** * Transmit a string to a list of connections ***/ int broadcast(int max_connects,int *fd_list,char *send_buffer) { int broadloop; /* Print send buffer to stdout & flush (for redirecting to a file) */ printf("%s",send_buffer); fflush(stdout); for (broadloop=0;broadloop0) NetPutString(fd_list[broadloop],send_buffer); } return 0; } /***************************************************************************** * Handle SIGINT & SIGTERM ***/ void signal_handler() { broadcast(CONNS,(int *)&fd_array,">>> Shutting down <<<\n"); server_down=1; } /***************************************************************************** * Main loop ***/ int main() { struct sockaddr_in server; fd_set readfds; char *buffer=malloc(BUFLEN); char *send_buffer=malloc(BUFLEN+10); int mastersocket; int newsocket; int new_conns; int addrlen=sizeof(struct sockaddr); int max_conns=sysconf(_SC_OPEN_MAX); int counter; /* check buffers were allocated ok */ if ((buffer==NULL) || (send_buffer==NULL)) { perror("Buffer allocation error"); exit(EXIT_FAILURE); } server_down=0; printf("To stop this server, type CTRL-C\n"); /* initialise the fd_array to zeros */ for (counter=0;counter0 then add it to the list to be checked */ for (counter=0;counter0) { printf("New socket open as file descriptor %d\n",newsocket); NetPutString(newsocket,"Welcome to the NetLib example server\n"); /* check if server reached maximum connections */ counter=0; while ((counter