0

Can someone explain to me what each part of this code is doing? It would be helpful if someone could give me a step by step explanation. Also, how could I upload files? How do I manipulate a ruby server in general?

#!/usr/bin/env ruby

require 'socket'
require 'cgi'

server = TCPServer.new('127.0.0.1', 8888)
puts 'Listening on 127.0.0.1:8888'

loop {
  client = server.accept

  first_request_header = client.gets
  resp = first_request_header

  headers = ['http/1.1 200 ok',
             "date: #{CGI.rfc1123_date(Time.now)}",
             'server: ruby',
             'content-type: text/html; charset=iso-8859-1',
            "content-length: #{resp.length}\r\n\r\n"].join("\r\n")
  client.puts headers          # send the time to the client
  client.puts resp
  client.close
}

1 Answer 1

2
#required gems
require 'socket'
require 'cgi'

#creating new connection to a local host on port 8888
server = TCPServer.new('127.0.0.1', 8888)
puts 'Listening on 127.0.0.1:8888'

loop {
  #looks like a client method call to open the connection
  client = server.accept
  first_request_header = client.gets
  resp = first_request_header

  #setting the request headers
  headers = ['http/1.1 200 ok',
             "date: #{CGI.rfc1123_date(Time.now)}",
             'server: ruby',
             'content-type: text/html; charset=iso-8859-1',
            "content-length: #{resp.length}\r\n\r\n"].join("\r\n")

  #inserts custom client headers into request
  client.puts headers         
  client.puts resp

  #closes client connection to local host
  client.close
}
Sign up to request clarification or add additional context in comments.

3 Comments

what is client.gets doing? What are request headers and why would you need to set them? What does inserting a header into a request mean?
also why does the output to the server seem to get cut off after 30 characters

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.