Select Git revision
testthree.crt
server.c 2.55 KiB
/*
|**************************************************|
|*| Computer Systems (COMP20023) 2018 Semester 1 |*|
|*| Assignment 1 - Multithreaded HTTP/1.0 Server |*|
|**************************************************|
|**| Student ID: |******| Name: |*******|
|**| 798839 |******| Saleh Ahmed Khan |*******|
|**************************************************|
|* Credit: Used Sample code from LMS for sockets *|
*/
#include "server.h"
int main(int argc, char *argv[]) {
/* Sample code starts here, not changed
or commented as per clarification
with the tutor via email */
int sockfd, newsockfd, portno;
char buffer[BUF];
struct sockaddr_in serv_addr, cli_addr;
socklen_t clilen;
int n;
if (argc < 2) {
fprintf(stderr, "Usage \"./name <port> ./<root>\"\n");
exit(1);
}
/* Create TCP socket */
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
perror("ERROR opening socket");
exit(1);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
/* Create address we're going to listen on (given port number)
- converted to network byte order & any IP address for
this machine */
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno); // store in machine-neutral format
/* Bind address to the socket */
if (bind(sockfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0) {
perror("ERROR on binding");
exit(1);
}
/* Listen on socket - means we're ready to accept connections -
incoming connection requests will be queued */
listen(sockfd,5);
clilen = sizeof(cli_addr);
/* End of sample code. Most of my own code starts here: */
char* root = argv[2];
while (INFINITE_LOOP) {
/* Accept a connection - block until a connection is ready to
be accepted. Get back a new file descriptor to communicate on. */
newsockfd = accept( sockfd, (struct sockaddr *) &cli_addr,
&clilen);
if (newsockfd < 0) {
continue;
}
/* Multithreading using fork(), based on clarification by Professor this is a valid alternative to pthreads.
Based on comparative testing vs pthreads this works
efficiently and makes code shorter and more readable.
*/
if (!fork()) {
close(sockfd);
/* Read characters from the connection, then process */
read(newsockfd, buffer, BUF-1);
parse_request_and_send_response(root, buffer, newsockfd);
close(newsockfd);
}
close(newsockfd);
}
/* close socket */
close(sockfd);
return 0;
}