Path: blob/master/concurrency-webserver/src/wclient.c
909 views
//1// client.c: A very, very primitive HTTP client.2//3// To run, try:4// client hostname portnumber filename5//6// Sends one HTTP request to the specified HTTP server.7// Prints out the HTTP response.8//9// For testing your server, you will want to modify this client.10// For example:11// You may want to make this multi-threaded so that you can12// send many requests simultaneously to the server.13//14// You may also want to be able to request different URIs;15// you may want to get more URIs from the command line16// or read the list from a file.17//18// When we test your server, we will be using modifications to this client.19//2021#include "io_helper.h"2223#define MAXBUF (8192)2425//26// Send an HTTP request for the specified file27//28void client_send(int fd, char *filename) {29char buf[MAXBUF];30char hostname[MAXBUF];3132gethostname_or_die(hostname, MAXBUF);3334/* Form and send the HTTP request */35sprintf(buf, "GET %s HTTP/1.1\n", filename);36sprintf(buf, "%shost: %s\n\r\n", buf, hostname);37write_or_die(fd, buf, strlen(buf));38}3940//41// Read the HTTP response and print it out42//43void client_print(int fd) {44char buf[MAXBUF];45int n;4647// Read and display the HTTP Header48n = readline_or_die(fd, buf, MAXBUF);49while (strcmp(buf, "\r\n") && (n > 0)) {50printf("Header: %s", buf);51n = readline_or_die(fd, buf, MAXBUF);5253// If you want to look for certain HTTP tags...54// int length = 0;55//if (sscanf(buf, "Content-Length: %d ", &length) == 1) {56// printf("Length = %d\n", length);57//}58}5960// Read and display the HTTP Body61n = readline_or_die(fd, buf, MAXBUF);62while (n > 0) {63printf("%s", buf);64n = readline_or_die(fd, buf, MAXBUF);65}66}6768int main(int argc, char *argv[]) {69char *host, *filename;70int port;71int clientfd;7273if (argc != 4) {74fprintf(stderr, "Usage: %s <host> <port> <filename>\n", argv[0]);75exit(1);76}7778host = argv[1];79port = atoi(argv[2]);80filename = argv[3];8182/* Open a single connection to the specified host and port */83clientfd = open_client_fd_or_die(host, port);8485client_send(clientfd, filename);86client_print(clientfd);8788close_or_die(clientfd);8990exit(0);91}929394