Reputation: 449
I am programming a TCP server in C++, and this is my first time doing it. The problem I am running into seems to be toward the bottom with the strcmp
function. I have established the server, then I fork my processes and run the request from the child process. This works fine. For some reason, when I input GET /stuff/
it won't accept GET
and automatically prints the error message "Invalid first argument"
. I have no space problems, so what's the deal? Any ideas are very much appreciated.
void processClientRequest(int connSock, struct sockaddr_in echoclient) //char *argv[] )
{
char buffer[256];
unsigned int recieved, count = 0;
if ((recieved = read(connSock, buffer, 256)) < 0) { //read a message from the client
perror ("Failed to recieve message");
exit (EXIT_FAILURE);
}
buffer[recieved] = '\0'; //ensure string is terminated
chomp(buffer); //remove trailing \r and \n
if (write(connSock, buffer, recieved) != recieved) {
perror ("Mismatch in number of echo'd bytes");
exit(EXIT_FAILURE);
}
// prepare argv array of strings
char *argv[] = { (char*)0, (char*)0, (char*)0, (char*)0, (char*)0, (char*)0, (char*)0 };
// parse command into words
for (char *p = strtok(buffer, " "); p; p = strtok(NULL, " "))
{ argv[count] = p;
count++;
}
cout << "THIS IS ARGV[0]" << argv[0] << endl; //debugging, for some reason will not print
if (strcmp (argv[0], "GET") == 0)
GET(connSock, argv[1]);
else if (strcmp(argv[0], "INFO") == 0)
INFO();
else
{
perror("Invalid first argument!");
exit(EXIT_FAILURE);
}
// run command and its arguments via execvp
/* if (execvp(argv[0], argv) < 0) {
perror("exec in child after fork");
exit(EXIT_FAILURE);
}*/
cerr << "Client(" << inet_ntoa(echoclient.sin_addr) << ") sent: " << buffer << endl;
}
Upvotes: 0
Views: 296
Reputation: 182753
The read
function doesn't receive messages, it receives bytes. If you want to receive messages, and you do, you have to write a function to receive them. That requires following the rules of the HTTP protocol to keep receiving bytes until you have the entire messsage, whether that's a line, the entire header, or whatever.
This has probably been said thousands of times, "TCP is a reliable byte-stream protocol that does not preserve application message boundaries." Until you 100% understand what TCP is, don't write code that uses TCP. It will never work correctly.
Upvotes: 1