Ruby TCPServer 调用 sock.recv 出错 提示: recv for buffered IO (IOError)

tablecell · 2019年11月08日 · 最后由 tablecell 回复于 2019年11月10日 · 4743 次阅读
require "socket"  
dts = TCPServer.open('127.0.0.1', 8080)  
client=0

loop { 
  Thread.start(dts.accept) do |sock|
      client = client+1

   req=' <--- ' 
     while line = sock.gets  and line !~ /^\s*$/
#     puts line
     req << line
   end

    puts "req is " ,req
 isget=     req.index('GET')
  if  isget   then 
      puts " is get "    

    body='<script>fetch("/data",{method:"post",body:JSON.stringify({"A":100})}).then( res=>(console.log(res) ))</script>'


else 
   puts " is post "  

    body=   sock.recv(1024)
end 
   headers = ["HTTP/1.0 200 OK",
            "Content-Type: text/html;charset=utf8",
            "Content-Length: #{body.length}\r\n\r\n"].join("\r\n")

  sock.write( headers+body)
  sleep(1)
  end
}

客户端用 浏览器 打开 http://localhost:8080/test

body= sock.read就好了,一般都用read或者read_nonblock,没见过用recv

piecehealth 回复

用 read 必须要读到固定长度的字节才返回 用 read_nonblock/recv_nonblock 也是报错

internal:prelude:73:in `__read_nonblock': A non-blocking socket operation could not be completed immediately. - read would block (IO::EWOULDBLOCKWaitReadable)

如果要实现 recv 那种收到多少就返回多少的功能 应该怎么写?

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