[ next ] [ prev ] [ contents ] [ up to Appendix C - Web Server Example ] Invitation To Ruby

A Web Server

  1: port = (ARGV[0] || 8888).to_i
  2: server = TCPServer.new('localhost', port)
  3: while (session = server.accept)
  4:   command, path, protocol = session.gets.split
  5:   filename = "." + path
  6:   if command == 'GET'
  7:     begin
  8:       case path
  9:       when '/time'
 10:         puts "Doing Time"
 11:         show_header(session, 'text/html')
 12:         session.print "<html><body><h1>#{Time.now}</h1></body></html>\r\n"
 13:       when /.*\.html?$/
 14:         puts "Sending HTML File: [#{filename}]"
 15:         show_header(session, 'text/html')
 16:         copyfile(filename, session)
 17:       else
 18:         puts "Sending Text File: [#{filename}]"
 19:         show_header(session, 'text/plain')
 20:         copyfile(filename, session)
 21:       end
 22:     rescue
 23:       session.print "File #{filename} Not Found\r\n"
 24:     end
 25:   end
 26:   session.close
 27: end

See Full Source Code


[ next ] [ prev ] [ contents ] [ up to Appendix C - Web Server Example ] Copyright 2002 by Jim Weirich.
All rights reserved.