/* Here we go... */ #include #include #include #include #include #include #include #include #include #include /* We wait in a loop for players to connect and tell us how many people are playing. Then, once all players have connected, then we broadcast the addresses of all players, and then start again. Note: We rely on our MAX_PLAYERS and the client's MAX_PLAYERS being the same. Otherwise we crash. */ #include "protocol.h" #define MAX_CONNECTIONS 64 #define UNCONNECTED 0 #define CONNECTED 1 #define ACTIVE 2 #define TIMEOUT 300 /* timeout in seconds */ typedef struct { int state; int sockfd; time_t timestamp; int player; int numplayers; unsigned char *packet; int packetlen; struct sockaddr_in raddr; } connection; connection players[MAX_CONNECTIONS]; /* This function disconnects a player */ void DisconnectPlayer(int which) { if ( players[which].state == ACTIVE ) (void) free(players[which].packet); close(players[which].sockfd); players[which].state = UNCONNECTED; printf("Player on slot %d has been disconnected.\n", which); } void SendError(int which, char *message) { unsigned char mesgbuf[BUFSIZ]; int mesglen; mesglen = (2+strlen(message)+1); if ( mesglen > BUFSIZ ) { fprintf(stderr, "Fatal error: error message too long!\n"); exit(3); } mesgbuf[0] = mesglen; mesgbuf[1] = NET_ABORT; strcpy((char *)&mesgbuf[2], message); printf("Sending error '%s' to player in slot %d\n", message, which); (void) write(players[which].sockfd, mesgbuf, mesglen); DisconnectPlayer(which); } /* Uh oh, a fatal error. Tell all currently connected players, and exit. */ void Fatal(char *message) { int i; for ( i=0; i TIMEOUT ) { SendError(i, "Server timed out waiting for packet"); } } } /* This is the function that makes the server go 'round. :) */ /* We check to see if all advertised players have connected, and if so we blast everyone's address to each player. */ void CheckNewGame(void) { unsigned char buffer[BUFSIZ]; int first, i; int numplayers, players_on; int positions[MAX_PLAYERS]; /* Find the first player */ for ( i=0, first=(-1); iraddr.sin_addr)); printf("Setting up player %d at host %s and port ", i+1, ptr); len += strlen(ptr)+1; ptr += strlen(ptr)+1; sprintf(ptr, "%d", ntohs(player->raddr.sin_port)); printf("%s\n", ptr); len += strlen(ptr)+1; ptr += strlen(ptr)+1; } buffer[0] = len; for ( i=0; i