Class: SimpleServer
- Inherits:
-
Object
- Object
- SimpleServer
- Defined in:
- lib/simple_server.rb
Constant Summary collapse
- WEB_ROOT =
'./public'- LOG =
Logging.setup
Instance Attribute Summary collapse
-
#level ⇒ Object
readonly
Returns the value of attribute level.
-
#output ⇒ Object
readonly
Returns the value of attribute output.
-
#server ⇒ Object
readonly
Returns the value of attribute server.
Instance Method Summary collapse
- #clean_path(path) ⇒ Object
-
#initialize(host = 'localhost', port = 2345) ⇒ SimpleServer
constructor
A new instance of SimpleServer.
- #run ⇒ Object
- #server_info ⇒ Object
Constructor Details
#initialize(host = 'localhost', port = 2345) ⇒ SimpleServer
Returns a new instance of SimpleServer.
14 15 16 17 |
# File 'lib/simple_server.rb', line 14 def initialize(host='localhost', port=2345) @server = TCPServer.new(host, port) LOG.debug("Server is set up.") end |
Instance Attribute Details
#level ⇒ Object (readonly)
Returns the value of attribute level.
7 8 9 |
# File 'lib/simple_server.rb', line 7 def level @level end |
#output ⇒ Object (readonly)
Returns the value of attribute output.
7 8 9 |
# File 'lib/simple_server.rb', line 7 def output @output end |
#server ⇒ Object (readonly)
Returns the value of attribute server.
7 8 9 |
# File 'lib/simple_server.rb', line 7 def server @server end |
Instance Method Details
#clean_path(path) ⇒ Object
19 20 21 22 23 24 25 26 27 28 |
# File 'lib/simple_server.rb', line 19 def clean_path(path) clean = [] parts = path.split("/") parts.each do |part| next if part.empty? || part == '.' part == '..' ? clean.pop : clean << part end File.join(WEB_ROOT, *clean) end |
#run ⇒ Object
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 |
# File 'lib/simple_server.rb', line 34 def run server_info begin loop do Thread.start(server.accept) do |socket| LOG.debug("Accepted socket: #{socket.inspect}") request = Request.parse(socket.gets) LOG.debug("Incoming request: #{request.inspect}") path = clean_path(request.resource) path = File.join(path, 'index.html') if File.directory?(path) LOG.debug("Requested path: #{path.inspect}") response = Response.build(path) socket.print response.header socket.print response.stream LOG.info(response.header) socket.close end end rescue Interrupt puts "\nExiting...Thank you for using this super awesome server." end end |
#server_info ⇒ Object
30 31 32 |
# File 'lib/simple_server.rb', line 30 def server_info puts "#{'-' * 30}\nWelcome to the Simple Server.\nPlease use CONTROL-C to exit.\n#{'-' * 30}\n\n" end |