Name: Anonymous 2008-05-08 0:11
Your job, shall you choose to accept it, is to build a very simple web server.
Here is a very basic and buggy first take... Try to make yours more beautiful. Good luck.
Here is a very basic and buggy first take... Try to make yours more beautiful. Good luck.
require "socket"
def respond(req, headers, sock)
puts req
if req == "/"
sock.print "HTTP/1.1 200 OK\r\n\r\n"
sock.puts "<html>"
Dir["*"].each do |file|
sock.puts "<a href=\"#{file}\">#{file}</a>"
end
sock.puts "</html>"
else
if File.exist?(Dir.pwd + req)
sock.print "HTTP/1.1 200 OK\r\n\r\n"
puts Dir.pwd + req
File.open(Dir.pwd + req) do |f|
f.each_line do |line|
sock.puts line
end
end
else
puts "Error"
sock.print "HTTP/1.1 404 Not Found\r\n\r\n"
sock.print "Object not found"
end
end
sock.close
end
def handle(sock)
headers = {}
req = nil
if sock.gets =~ /GET ([^\s]+) HTTP\/1.1/
if req == nil
req = $1
end
while true
l = sock.gets
if l == "\r\n"
respond(req, headers, sock)
else
if l =~ /([^\s]+):\s*([^\s]+)/
headers[$1] = $2
end
end
end
end
end
servar = TCPServer.new("localhost", 9000)
threads = []
while sock = servar.accept
threads << Thread.new do
handle(sock)
end
end