/* * This is a better server than simple_server.c * I'm only going to comment changes from simple_server.c * So if there's something that doesn't make any sense in here, maybe look at that one. */ #include #include #include #include #include #include #include #include #include #include "looking_glass.h" int skt; void shut_down_server(int signal){ printf("\nDoing everything we need to do to shut down the server\n"); close(skt); exit(0); } int main(int argc, char ** argv){ uint16_t listen_port = 5141; // 5141 is the default if(argc > 1){ listen_port = atoi(argv[1]); if(listen_port < 1){ printf("Invalid port: %s\n", argv[1]); exit(1); } printf("Will listen on port %d\n", listen_port); } else { printf("No port specified, defaulting to %d\n", listen_port); } struct sigaction sa; sa.sa_handler = shut_down_server; sigaction(SIGINT, &sa, 0); struct sockaddr_in sad; sad.sin_port = htons(listen_port); sad.sin_addr.s_addr = INADDR_ANY; sad.sin_family = AF_INET; skt = socket(AF_INET, SOCK_STREAM, 0); // Step 1 if(skt == -1){ perror("socket"); return 1; } if( bind(skt, (struct sockaddr *)(&sad), sizeof(struct sockaddr_in)) ){ // step 2 perror("bind"); return 1; } if( listen(skt, 5) ){ // step 3 perror("listen"); return 1; } int client_fd; struct sockaddr_in client_address; socklen_t address_size = sizeof(struct sockaddr_in); while(1){ client_fd = accept(skt, (struct sockaddr *)(&client_address), &address_size); // step 4 printf("Connection made from address %s\n", inet_ntoa(client_address.sin_addr)); /* Sending method: Array of Characters */ unsigned char version_message[5]; version_message[0] = 14; version_message[1] = 5; version_message[2] = 7; version_message[3] = 0; version_message[4] = 0; write(client_fd, version_message, 5); // next: Send a game message out // type: 11 (1 byte) // initial points: 637 (2 bytes) // stat limit: 637 (2 bytes) // description length: strlen(description) (2 bytes) // description: ... char *description = looking_glass; /* Sending method: Individual Variables */ char type = 11; uint16_t initial_points = 637; uint16_t stat_limit = 637; uint16_t description_length = strlen(description); // description was specified above, so we could use strlen printf("Description length is %d\n", description_length); write(client_fd, &type, 1); write(client_fd, &initial_points, 2); write(client_fd, &stat_limit, 2); write(client_fd, &description_length, 2); write(client_fd, description, description_length); close(client_fd); } return 0; }