Skip to content

Instantly share code, notes, and snippets.

@dcki
Last active May 3, 2016 03:38
Show Gist options
  • Save dcki/7da36e391bcf93e99b171dc1efb5d73a to your computer and use it in GitHub Desktop.
Save dcki/7da36e391bcf93e99b171dc1efb5d73a to your computer and use it in GitHub Desktop.
# Below, "telnet curl" means curl telnet://localhost:8080/
# "http curl" means curl http://localhost:8080/
# telnet curl is sometimes used here because it approximates a raw tcp mode for
# curl. On OS X telnet curl waits for more input on the client side, not sure
# why. Linux telnet curl exits immediately, which is desirable for these tests.
require 'socket'
file_counter = 0
Socket.tcp_server_loop(8080) do |sock, client_addrinfo|
file_counter += 1
# Oddly, even if you only specify the first line of the the HTTP response
# header you can still make curl happy by making the server concurrent.
Thread.new(file_counter) do |file_counter|
begin
filepath = "/tmp/#{file_counter}"
# touch the file to make this thread respond to the request.
loop do
puts "Looking for #{filepath}"
break if File.exist? filepath
sleep 1
end
content = "#{file_counter}\n"
# Only telnet curl (see above) is okay with this.
#sock.write "#{content}"
# If this is all you send then Firefox and http curl will sometimes be
# happy, sometimes not. Chrome never accepts this. http curl is also
# always happy if the server is concurrent (see above).
#sock.write "HTTP/1.1 200 OK\n\n#{content}"
# Only the first byte of content will be rendered, even if the actual
# content sent is longer.
#sock.write "HTTP/1.1 200 OK\nContent-Length: 1\n\n#{content}"
# Everybody's happy!
sock.write "HTTP/1.1 200 OK\nContent-Length: #{content.size}\n\n#{content}"
# If Content-Length is longer than the content, everybody throws an error
# because they expected more content before the connection is closed.
#sock.write "HTTP/1.1 200 OK\nContent-Length: #{content.size + 1}\n\n#{content}"
ensure
sock.close
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment