Skip to content

Instantly share code, notes, and snippets.

@FooBarWidget
Created April 21, 2011 16:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FooBarWidget/934946 to your computer and use it in GitHub Desktop.
Save FooBarWidget/934946 to your computer and use it in GitHub Desktop.
require 'socket'
require 'thread'
FILENAME = ARGV[0] || 'doc/asciidoc.html'
BLOCK_SIZE = 128
SLEEP_TIME = 0.01
def serve_client(client, thread_id)
client.readline =~ /^([A-Z]+) (.+) HTTP/
path = $2
while client.readline != "\r\n"
# Do nothing.
end
client.write("HTTP/1.1 200 OK\r\n")
client.write("Connection: close\r\n")
if path == "/"
size = File.size(FILENAME)
client.write("Content-Type: text/html\r\n")
client.write("\r\n")
counter = 0
File.open(FILENAME, 'rb') do |f|
while !f.eof?
data = f.read(BLOCK_SIZE)
client.write(data)
counter += data.size
printf "[Thr-%d] %d/%d (%.1f%%)\n",
thread_id,
counter,
size,
counter * 100.0 / size
sleep SLEEP_TIME
end
end
elsif path =~ /\.js$/
client.write("Content-Type: text/javascript\r\n")
client.write("\r\n")
client.write(File.read("javascripts/#{path}"))
elsif path =~ /\.css$/
client.write("Content-Type: text/css\r\n")
client.write("\r\n")
client.write(File.read("stylesheets/#{path}"))
else
if path =~ /\.png$/
client.write("Content-Type: image/png\r\n")
else
client.write("Content-Type: image/plain\r\n")
end
client.write("\r\n")
end
client.close_write
client.read
rescue Errno::EPIPE
# Do nothing.
ensure
client.close
end
last_thread_id = 0
server = TCPServer.new('localhost', 3000)
while c = server.accept
t = Thread.new(c, last_thread_id) do |client, thread_id|
serve_client(c, thread_id)
end
t.abort_on_exception = true
last_thread_id += 1
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment