Search code examples
chttphttp-headersiot

Raw http server: send image issue


I'am working with kind of IoT device. Finaly I've got simple httpd server to work, and simple html pages works like a charm, but browser does not recognise images. I think this is http header issue, but i do not know what is exacly wrong.

For example, my test page look like this:

<html>
<head><title>test page</title></head>
<body>
hello world!
<img src="img.png">
</body>
</html>

If i go to http://de.vi.ce.ip/ 2 reqests are generated:

GET / HTTP/1.1\r\n
Accept text/html, application/xhtml+xml, */*\r\n
Accept-Language: en-EN\r\n
...

GET /img.png HTTP/1.1\r\n
Accept image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5\r\n
Accept-Language: en-EN\r\n
...

To witch my server responds with:

HTTP/1.0 200 OK\r\n
Content-Type: text/html\r\n
Content-Length: 131\r\n
\r\n
<page data>

HTTP/1.0 200 OK\r\n
Content-Type: image/png\r\n
Content-Length: 5627\r\n
\r\n
<image binary data>

As the result i can see the text, but images are broken. I've tryed few more parameters like Connection: close, Accept-Ranges: bytes, Content-Location (path). I've tryed jpeg image under Content-Type: image/jpeg with no luck. I'am certain that image sent correctly.


Solution

  • I've made exactly the same - raw http server for IoT and your response looks absolutely correct. Try check following:

    • You correctly flush the socket before closing it. If you call close() right after send(), you will likely encounter this problem - data has not been correctly written

    • The Content-Length should be exactly the size of your file. Make sure you are not counting \r\n bytes of http response. Browser may still wait for tail bytes

    • Finally, get the browser network logs :)