0

I am using the joyent http-parser and lib event to create my own simple web server in C.

I have it connecting to the port and receiving the HTTP requests fine, however, I am not able to send a response using the socket.

So in one window I enter:

$ curl localhost:5555/a.txt

and in my server I receive and correctly handled it. TO the point I do the following:

   http_data_cb* message_complete_req_callback(http_parser* parser)
{
    int i;
    http_request_t* http_request = parser->data;
    http_response_t* http_response = generate_response(http_request);
    printf("Writing %d:\n%s", strlen(http_response->full_message), http_response->full_message);
    i = write(http_request->fd, http_response->full_message, strlen(http_response->full_message));
    fsync(http_request->fd);
    printf("Wrote: %d\n", i);
    return 0;
}

Which prints the following:

Writing 96:
HTTP/1.0 200 OK
Tue, 04 Aug 2015 10:20:58 AEST
Server: mywebserver/jnd
Connection: close

Wrote: 96

However my curl instance doesn't receive anything. Any ideas?

Thanks in advance.

Philip Couling
  • 13,581
  • 5
  • 53
  • 85
jnd
  • 754
  • 9
  • 20
  • Why do you cast `http_request` to the type it already has? In any case, code that isn't a minimal complete example is difficult to handle for us. – Jens Gustedt Aug 10 '15 at 06:27
  • Also your `printf` calls are bogus and shouldn't have passed a decent compiler: the correct format for `size_t` is `%zu` and your last one has a `%d` and no function argument for it. This alone could be a reason that your program crashes. – Jens Gustedt Aug 10 '15 at 06:48
  • What was the value of `i` returned by `write()`? and why didn't you test it for an error? And why are you calling `printf()` with a `"%d"` format and no argument? – user207421 Aug 10 '15 at 06:55
  • Sorry @JensGustedt I fixed that up and it seems to say it printed the correct number of bytes present. – jnd Aug 10 '15 at 07:01

1 Answers1

0

Your response contains no data, just headers. Curl strips off the headers and just prints the content. Not only that but you're responding with HTTP/1.0 which is a long way out of date. As it happens, the Connection: close only makes sense in 1.1 as 1.0 does not support keeping a connection open.

For curl to report anything you need to send some content. I'd expect the output to be something like:

Writing 128:
HTTP/1.1 200 OK
Tue, 04 Aug 2015 10:20:58 AEST
Server: mywebserver/jnd
Connection: close
Content-Length: 12

Hello World
Wrote: 128

Which would trigger curl to print:

Hello World

Notice the 12 character content length includes 1 character for the line feed. The content is Hello World<lf>.

Philip Couling
  • 13,581
  • 5
  • 53
  • 85