This has gone through a few incarnations, the first of which could only serve one client at a time, i then overcame this via forking, and then, as my skills progressed i decided to make a separate thread for each client, whilst there's still room for improvement (security, using net::http etc) its fairly respectable given its size methinks.
Quote: [b]code:[/b]<hr>
require 'socket'
def main
listener = TCPServer.new("localhost", (ARGV[0]||80).to_i)
loop do
session = listener.accept
Thread.new(session) do |s|
req = nil
session.each do |line|
if line =~ /^GET (.+) HTTP/
req $1
end
break if line.strip.empty?
end
if req
session.puts http_file("." + req)
else
session.puts err_page("error")
end
s.close
end
end
end
Header = "HTTP/1.1 200/OKnContent-type: text/htmlrnrn"
def err_page(title, message)
Header+
"<html><head><title>#{title}</title></head>n" +
"<body>[b]Error:[/b]#{message}</body></html>n"
end
def http_file(filename)
if filename =~ /../
return err_page 'Error', '".." in URL not allowed'
else
begin
f = File.open(filename,"r")
contents = f.read
f.close
Header + contents
rescue
err_page 'Error', $!.to_s.gsub(/n/, " ")
end
end
end
main
<hr>
This article was originally written by Pigsbig78 |