Ruby 模拟 curl 的请求 sock.gets 很长时间才得到响应,但是 curl 很快就返回结果

tablecell · 2016年11月30日 · 最后由 luikore 回复于 2016年12月27日 · 1876 次阅读
require 'socket'  
hostname='www.ruby-china.org'
#ua='Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.79 Safari/535.11'
header={'User-Agent'=>'curl/7.30.0',
'Host'=>hostname,
'Accept'=>'*/*'
 }
req="GET / HTTP/1.1\r\n"
header.each {|key, value| req+= "#{key}: #{value}\r\n" }
req+="\r\n"
port =80
sock = TCPSocket.open(hostname, port)
 sock.print req

  while line = sock.gets   
    puts line.chop       
  end
sock.close               



你可以先 sock.close_write 再读,马上就能读到 EOF.

不然只能按照 HTTP 协议的,解析响应 header 的 Content-Length 来读。

#1 楼 @luikore 文档上写的是 Disallows further write using shutdown system call. 这个 socket.close_write 与 直接 socket.close 有什么区别吗?

#2 楼 @tablecell 你可以查一查怎么实现 pipe,然后就可以理解了。

#2 楼 @tablecell 有区别,close 了 write 但没 close read.

需要 登录 后方可回复, 如果你还没有账号请 注册新账号