Skip to content
Snippets Groups Projects
Commit 74f14a7f authored by ChouTatsumi's avatar ChouTatsumi
Browse files

simplify all normal pages

parent 1634b23e
No related branches found
No related tags found
No related merge requests found
File added
......@@ -51,9 +51,8 @@ typedef enum { GET, POST, UNKNOWN } METHOD;
void run_server(const char* ip, const int port);
int create_server_socket(const char* ip, const int port);
static bool handle_http_request(int sockfd);
bool show_intro_page(int sockfd);
bool show_page(int sockfd, char* htmldir);
bool show_start_page(int sockfd, char* username);
bool show_first_turn_page(int sockfd);
int main(int argc, char** argv) {
int port;
......@@ -210,16 +209,20 @@ static bool handle_http_request(int sockfd) {
// contents of each pages
if (*curr == ' ') {
if (method == GET) {
return show_intro_page(sockfd);
return show_page(sockfd, INTRO_PAGE);
} else if (method == POST) {
if (strstr(buff, "user=") != NULL) {
char* username = strstr(buff, "user=") + 5;
return show_start_page(sockfd, username);
} else if (strstr(buff, "quit=") != NULL) {
return show_page(sockfd, GAMEOVER_PAGE);
}
} else
// never used, just for completeness
fprintf(stderr, "no other methods supported");
} else if (*curr == '?') {
if (method == GET) {
return show_first_turn_page(sockfd);
return show_page(sockfd, FIRST_TURN_PAGE);
}
// else if (method == POST) {}
else
......@@ -236,13 +239,13 @@ static bool handle_http_request(int sockfd) {
return true;
}
bool show_intro_page(int sockfd) {
bool show_page(int sockfd, char* htmldir) {
char buff[2049];
int n;
// get the size of the file
struct stat st;
stat(INTRO_PAGE, &st);
stat(htmldir, &st);
n = sprintf(buff, HTTP_200_FORMAT, st.st_size);
// send the header first
if (write(sockfd, buff, n) < 0) {
......@@ -250,7 +253,7 @@ bool show_intro_page(int sockfd) {
return false;
}
// send the file
int filefd = open(INTRO_PAGE, O_RDONLY);
int filefd = open(htmldir, O_RDONLY);
do {
n = sendfile(sockfd, filefd, NULL, 2048);
} while (n > 0);
......@@ -260,6 +263,7 @@ bool show_intro_page(int sockfd) {
return false;
}
close(filefd);
return true;
}
......@@ -314,31 +318,3 @@ bool show_start_page(int sockfd, char *username) {
return true;
}
\ No newline at end of file
bool show_first_turn_page(int sockfd){
char buff[2049];
int n;
// get the size of the file
struct stat st;
stat(FIRST_TURN_PAGE, &st);
n = sprintf(buff, HTTP_200_FORMAT, st.st_size);
// send the header first
if (write(sockfd, buff, n) < 0) {
perror("write");
return false;
}
// send the file
int filefd = open(FIRST_TURN_PAGE, O_RDONLY);
do {
n = sendfile(sockfd, filefd, NULL, 2048);
} while (n > 0);
if (n < 0) {
perror("sendfile");
close(filefd);
return false;
}
close(filefd);
return true;
}
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment