Search code examples
rubyimagesocketshttpservertcpserver

Ruby Socket TCPServer send png image to client


I have an http server using sockets that gets all client data, and sends back data. I am successfully able to send back HTML to the client (my web browser) but whenever I try and send an image, I get a small white square no matter what image I send.

The code:

#Generate and send response
def response(client, response = 200, headers, data)
    client.print "HTTP/1.1 #{response.to_s}\r\n"
    headers_s = ""
    for h in headers do
        headers_s = headers_s + h + "\n"
    end
    client.print "#{headers_s}\r\n"
    client.print "\r\n"
    client.print data.to_s
end

response(client, 200, ["Content-Type: image/png"], File.read("./very_cool_picture.png"))

I probably am reading the image wrong, but I am not sure. Also, sending back other binary data such as executables does not work properly either even with the correct headers.

There is also more code that I did not show because it was excessive and irrelevant that accepts the clients, parses requests, etc.


Solution

  • You have an extra \r\n between the headers and the data. After each header you add a \n (should really be a \r\n), then when you print them out you add another (client.print "#{headers_s}\r\n"), and then finally you write out another. This extra two bytes is resulting in the browser seeing invalid PNG data.

    Removing the line client.print "\r\n" should fix your issue.

    (You should probably also send a Content-Length header, although it will still work without one.)