1、typedef struct int serverPort; char methodMAXLINE,urlMAXLINE; char versionMAXLINE,hostnameMAXLINE,pathMAXLINE; requestHeader;struct cacheSet char hostnameMAXLINE; / hostname char pathMAXLINE; / path struct cacheSet* next; / pointer to next cache set char* buffer; / buffer pointer int time; / time st
2、amp int len; / buffer size;/*-*/void *doit(void*);struct cacheSet *cacheSearch(char *hostname, char *path);struct cacheSet *cacheFindLRU(int len);int cacheAdd(char *hostname, char *path, char *buf, int len);int globalTime = 0;struct cacheSet* cache;sem_t mutex_time;int readcnt = 0;sem_t mutex, w;sem
3、_t mutexHostName;/*-*/int main (int argc, char *argv ) int fd; if(fd=open(output.txt,O_RDWR,0)0) dup2(fd,1); pthread_t tid; struct sockaddr_in clientaddr; int listenfd; int *connfdp; int port; socklen_t clientLen = sizeof(struct sockaddr_in); / initilize cache cache = malloc(sizeof(struct cacheSet);
4、 if(cache = NULL) fprintf(stderr, fail to malloc cache.n); exit(1); strcpy(cache-hostname, path, cache-next = NULL;buffer = NULL;time = 0;len = 0; / initilize semaphore sem_init(&mutex_time,0,1); sem_init(&mutex,0,1);w,0,1);mutexHostName,0,1); /* exam the portnumber */ if (argc != 2)No portnumber!n
5、/* ignore the SIGPIPE*/ Signal(SIGPIPE,SIG_IGN); port = atoi(argv1); if (listenfd = open_listenfd(port) 0) fprintf(stderr,fail to open listenfd! exit(-1); /* create a new thread */ while(1) if (connfdp = (int *) malloc(sizeof(int)= NULL)fail to get space from heap! continue; if (*connfdp = accept(li
6、stenfd,(SA *)&clientaddr,&clientLen) url,http:/,7) /* surpass */ char *first=header-url+7; char *as=header-url; while(*first) *as=*first; as+; first+; *as=0 /* whether path is the root directory */(ptr = strchr(header-url,/) strcpy(header-path,/ /* get the path*/ elsepath,ptr); /* get the hostname *
7、/ length = strlen(header-url); for(i=0;iurli = ) break;: header-hostnamei = header-urli;hostnamei = /* get port number */ if (header-) i+;url+i); for(j=0;j+,i+) portj = header- portj = serverPort = atoi(port); * serve the single clientvoid *doit(void *vargp) rio_t clientRio,serverRio; int connfd = *
8、(int *)vargp; char bufMAXLINE, recBufMAX_OBJECT_SIZE; requestHeader header; int connfd2server; struct cacheSet* set; int lenSum = 0; free(vargp); tid = pthread_self(); if (pthread_detach(tid) !fail to detach thread:%dn,(int) tid); close(connfd); pthread_exit(NULL); /* read the first line of header i
9、n the request*/ rio_readinitb(&clientRio,connfd); if (rio_readlineb(&clientRio,buf,MAXLINE)0)fail to read the first line from the request! dbg_printf(buf=%sn,buf); sscanf(buf,%s %s %s,header.method,header.url,header.version); dbg_printf(method=%s,url=%s,version=%sn /* only surpport GET method*/ if (strcmp(header.method,GET)we cannot forward %s method!,header.method); if (parse_uri(&header,&clientRio)fail to parse the header)!serverPort=%d,hostname=%sn,header.serverPort,header.hostnam
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1