I’m trying to write a TCP client that does the following things:
1. Establish TCP connection to webserver
2. Accept GET request command from user's console
3. Client should get a reply back from webserver after each GET request.
I’m having a difficult time for the 3rd condition. I did not receive any response back from the webserver.
Here is my code:
s = connectTCP(host, service);
while (fgets(buf, sizeof(buf), stdin)) {
buf[LINELEN-2]='\r'; /* ensure catridge return */
buf[LINELEN-1]='\n'; /* ensure line feed return */
buf[LINELEN] = '\0'; /* ensure line null-terminated */
outchars = strlen(buf);
(void) write(s, buf, outchars);
printf("Start reading from socket...\n");
fflush(stdout);
while( (n = read(s, buf, LINELEN)) > 0) {
buf[n] = '\0'; /* ensure null-terminated */
(void) fputs( buf, stdout );
fflush(stdout);
}
}
An HTTP request is terminated with two carriage-return–linefeed (“\r\n\r\n”) sequences. The way you’re constructing your request won’t even ensure it has one. Maybe instead something like: