-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.rb
More file actions
42 lines (34 loc) · 1.68 KB
/
server.rb
File metadata and controls
42 lines (34 loc) · 1.68 KB
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
require 'socket' # Require socket from Ruby Standard Library (stdlib)
host = 'localhost'
port = 2000
server = TCPServer.open(host, port) # Socket to listen to defined host and port
puts "Server started on #{host}:#{port} ..." # Output to stdout that server started
loop do # Server runs forever
client = server.accept # Wait for a client to connect. Accept returns a TCPSocket
lines = []
while (line = client.gets) && !line.chomp.empty? # Read the request and collect it until it's empty
lines << line.chomp
end
puts lines # Output the full request to stdout
filename = lines[0].gsub(/GET \//, '').gsub(/\ HTTP.*/, '')
if File.exists?(filename)
response_body = File.read(filename)
success_header = []
success_header << "HTTP/1.1 200 OK"
success_header << "Content-Type: text/html" # should reflect the appropriate content type (HTML, CSS, text, etc)
success_header << "Content-Length: #{response_body.length}" # should be the actual size of the response body
success_header << "Connection: close"
header = success_header.join("\r\n")
else
response_body = "File Not Found\n" # need to indicate end of the string with \n
not_found_header = []
not_found_header << "HTTP/1.1 404 Not Found"
not_found_header << "Content-Type: text/plain"
not_found_header << "Content-Length: #{response_body.length}"
not_found_header << "Connection: close"
header = not_found_header.join ("\n\n")
end
response = [header, response_body].join("\r\n\r\n")
client.puts(response)
response = [header, response_body].join("\r\n\r\n")
end