Skip to content

Instantly share code, notes, and snippets.

@amarcher
Created March 27, 2015 01:27
Show Gist options
  • Save amarcher/88ce198e5638a76c13ee to your computer and use it in GitHub Desktop.
Save amarcher/88ce198e5638a76c13ee to your computer and use it in GitHub Desktop.
HTTP Server
require 'socket'
server = TCPServer.new(2000)
# loop do
# client = server.accept
# client.puts "Hi"
# client.close
# end
# loop do
# client = server.accept
# puts "I got a client"
# message = client.gets.chomp
# client.puts "Hi #{message}"
# client.close
# end
# loop do
# client = server.accept
# puts "I got a client"
# message = ""
# while (line = client.gets)
# break if (line.empty? || line == "\n" || line == "\r\n")
# message << line
# end
# client.close
# puts message # on the server
# end
# do example with chrome and talk about the http request format
# loop do
# client = server.accept
# puts "I got a client"
# message = ""
# while (line = client.gets)
# break if (line.empty? || line == "\n" || line == "\r\n")
# message << line
# end
# first_line = message.split("\r\n").first
# method, resource, version = first_line.split(" ")
# if resource == "/hello"
# client.puts "goodbye"
# else
# client.puts "other"
# end
# client.close
# puts message # on the server
# end
loop do
client = server.accept
puts "I got a client"
message = ""
while (line = client.gets)
break if (line.empty? || line == "\n" || line == "\r\n")
message << line
end
first_line = message.split("\r\n").first
method, resource, version = first_line.split(" ")
if resource == "/hello"
body=<<-htm
<html>
<head>
<title>Hello</title>
</head>
<body>
<H1>Hi</H1>
<img src="http://www.thehackerati.com/blog/assets/img/dbc.png" alt="Dev Bootcamp home">'
</body>
</html>
htm
else
body = "other"
end
response = <<-res
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Connection: close
Content-Length: #{body.length}
Last-Modified: Thu, 26 Mar 2015 23:16:16 GMT
Set-Cookie: Key=Value!!
#{body}
res
client.puts response
client.close
puts message # on the server
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment