public
Created

  • Download Gist
gistfile1.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
require 'socket'
require 'celluloid'
 
class Query
attr_accessor :type, :url, :other
 
def initialize (query_string)
@type, @url, @other = query_string.split " "
end
 
end
 
class AnswerWorker
include Celluloid
 
def process_get(query)
dir_path = "server"
filepath = dir_path + query.url
 
if File.exists? filepath
@client.puts (File.open(filepath).read)
else
@client.puts "Can't find file"
end
 
end
 
def process_req(query)
process_get query if query.type == "GET"
end
 
def start(client)
@client = client
 
headers = "HTTP/1.1 200 OK\r\nDate: Tue, 14 Dec 2010 10:48:45 GMT\r\nServer: Ruby\r\nContent-Type: text/html; charset=iso-8859-1\r\n\r\n"
client.puts headers
loop {
query = Query.new client.readline
process_req query
}
 
end
end
 
class HTTPServer
include Celluloid
 
def initialize(port)
@port = port
end
 
def start
@server = TCPServer.new(@port)
client = nil
pool = AnswerWorker.pool(size: 50)
 
loop {
client = @server.accept
pool.start! client
}
end
end
 
hs = HTTPServer.new 3000
hs.start

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.