0

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.

3
  • 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. Commented 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 that Commented Mar 18, 2012 at 13:43
  • check scribd.com/doc/20755982/The-Ruby-1-9-x-Web-Servers-Booklet Commented Mar 18, 2012 at 13:48

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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 ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.