-1

I'm trying to create a server in C sockets that will allow file uploads through HTTP. The problem I'm having is that I get a very good chunk of the HTTP content but then it just stops sending and begins hanging, perhaps waiting for a response or something? But since recv never hits 0 it never gets to my response. (not sure thats even the reason why).

I looked around on google but most answers are about receiving data and looping to receive more when I'm already doing that.

Heres the code:

            fp = fopen("fileName", "a");

            for(;;)
            {

                ret = recv(fd, buffer, BUFSIZE, 0);

                if(ret == 0){

\\ Never gets here unless I cancel the web request manually (pressing x where refresh usually is)

                    printf("Finished recieving");

                    char* sendHeader = "HTTP/1.1 200 OK\nContent-Type: text/plain\nContent-Length: 8\n\nRecieved";
                    write(fd, sendHeader, strlen(sendHeader));

                    break;
                }

                if(ret == -1) {
                    printf("Error recieving");
                    break;
                }

                fprintf(fp, "%s", buffer);
            }

            fclose(fp);

Right now i'm just taking the file contents and appending it to a file.

The actual result's I'm getting is:

(using ... to abbreviate)


--WebKitFormBoundaryRMGRl...
Content-Dispotion: form-data; name="filetoUpload"; filename...;
Content-type: application/octet-stream

\n

Actual file contents

\n

--WebKitFormBoundaryRMGRl...
Content-Disposition: form data; name="submit"

Upload License 
--WebKitFormBoundaryRMGRl...

Begins writing file contents again, writes about 10 lines, then hangs until I manually cancel request

When I print the byte values, i fill the buffer 2 times then the 3rd time it doesn't completely fill it and just hangs waiting?

Any ideas?

iG Cloud
  • 47
  • 1
  • 7

1 Answers1

2

But since recv never hits 0 it never gets to my response ...

recv will return 0 if the client shuts down the connection. But the client will not shut down the connection since it want to receive the response (ok, it could shut down for writing then) and maybe wants to send more requests (HTTP persistent connection).

Instead you have to parse the HTTP request to figure out how much data the client will send in the body. The usual way to do this is by setting the Content-length header to the size of the body. If the size is not known up-front the client might use chunked transfer encoding though were each chunk is prefixed by its length (in hex).

Or in other words: if you are trying to implement HTTP then please make yourself familiar with the standard by studying it and not by making just assumptions. That's what standards are actually for.

Community
  • 1
  • 1
Steffen Ullrich
  • 114,247
  • 10
  • 131
  • 172