Mr. Kennedy Mr. Kennedy - 2 months ago 17
Ruby Question

Basic Ruby http server not displaying .jpg to localhost on win7?

This http script works just fine from my gnome-terminal on Ubuntu (and per Aleksey, on Mac), but on win7, a small square gets loaded in the chrome browser. What do I need to do to get the JPEG sent through local host so it displays in the win7 browser? Per Holger's comment, I need to address the content encoding, but everything I've tried so far makes no difference on win7 (and still loads fine in Ubuntu without any explicit content encoding). ?.

PS C:\Users\user_name\Ruby\http_test> ls
basic_http.rb
lolcat.jpg
PS C:\Users\user_name\Ruby\http_test> ruby basic_http.rb




# very basic http server

require 'socket'

def send_200(socket, content)
socket.puts "HTTP/1.1 200 OK\r\n\r\n#{content}" # <-- Correct? (Per Holger)
socket.close
end

server = TCPServer.new 2016

loop do
Thread.start(server.accept) do |client|
request = client.gets
if request.start_with?("GET")
url = request.split(" ")[1]
if url.start_with?("/images/")
file = url.sub("/images/", "")
picture = File.read(file)
send_200(client, picture)
else
send_200(client, "hello!")
end
end
end
end


FWIW: Ruby 2.2, win7 & coding along with this demo.

enter image description here

Answer

You just have a typo in variable name.
You read file to pictures

pictures = File.read(file)

but you send it as picture

send_200(client, picture)

So you just need to edit variable name.

Maybe it would be a good idea to wrap request procession into begin block.

Thread.start(server.accept) do |client|
  begin
    ...
  rescue => ex
    puts ex
  end
end

This way you can see if something goes wrong.

Comments