I want to learn how to create a simple local server in ruby like maybe using webbrick. The main purpose here is that I am creating a web application and I want to do it myself without using any existing framework, so that I can learn the inner workings.
-
Take a look at an existing framework for the basics, or do a quick search for examples--there used to be several around. I accidentally re-created a really crappy Sinatra along with a DSL for rapidly prototyping site flow/forms/etc in under 100-200 lines of code; it's a good exercise.Dave Newton– Dave Newton2012-03-18 13:36:28 +00:00Commented Mar 18, 2012 at 13:36
-
i did google it but could not find whta i was looking for, they all relate to rails andinstalling rails on linux and stuffs like thatmonk– monk2012-03-18 13:43:20 +00:00Commented Mar 18, 2012 at 13:43
-
check scribd.com/doc/20755982/The-Ruby-1-9-x-Web-Servers-Bookletemre nevayeshirazi– emre nevayeshirazi2012-03-18 13:48:04 +00:00Commented Mar 18, 2012 at 13:48
Add a comment
|
1 Answer
I think you just need to start doing it.
My starting server:
require 'socket'
server = TCPServer.new '127.0.0.1', 8888
while session = server.accept
session.print "HTTP/1.1 200/OK\r\nContent-type:text/html\r\n\r\n"
if request = session.gets
filename = request.gsub(/GET\ \//, '').gsub(/\ HTTP.*/, '').chomp
filename = "index.html" if filename == ""
session.print "You asked for a file called #{filename}"
end
session.close
end
Of course, based on the filename you should try to fetch a file and send it to the client, maybe something like:
displayfile = File.open(filename, 'r')
content = displayfile.read()
session.print content
well if you want to learn, just start coding and trying different things, you may also look at the source code of some webservers on github. But, there is no point in posting here their code.
I just showed you the really basics.
1 Comment
monk
i run your code first time it works but the second time firefox says Unable to connect and i could not run it even by changing port number. whats the problem ?