2013-03-10 84 views
1

有人可以向我解釋這段代碼的每個部分在做什麼? 如果有人能給我一步一步的解釋,這將是有益的。 另外,我怎麼上傳文件? 如何操作一般的紅寶石服務器?Ruby TCP服務器基礎知識

#!/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
#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 
} 
+0

什麼client.gets在做什麼?什麼是請求標題以及爲什麼你需要設置它們?在請求中插入標頭意味着什麼? – nlsun 2013-03-10 04:40:49

+0

下面是'.gets'所做的:http://www.ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/Socket.html – BlackHatSamurai 2013-03-10 05:05:23

+0

也是爲什麼輸出到服務器似乎被切斷30個字符後關閉 – nlsun 2013-03-10 06:13:11