代码之家  ›  专栏  ›  技术社区  ›  Ceilingfish

在多线程环境中从ruby中的套接字读取数据

  •  0
  • Ceilingfish  · 技术社区  · 15 年前

    我试图通过ruby中的套接字读取HTTP数据包,由于某些原因,我的代码在调用recv时一直阻塞

    socket = TCPSocket.new("localhost",80)
    socket.send r.join("\r\n"), 0
    socket.flush
    #We're only interested in the string "HTTP/1.1 XXX"
    if http_status = get_http_status(socket.recv_nonblock(12))
        if http_status == 200
            $logger.info "Wrote #{message_packet}"
        else
            $logger.warn "Resubmitting message because #{line} is not 200"
            @queue.publish(message) 
        end
    end
    
    #Get rid of the rest of the content
    the_rest = socket.recv(1000)
    while(the_rest != "") do
        the_rest = socket.recv(1000)    
    end
    

    据我所知 recv

    1 回复  |  直到 15 年前
        1
  •  0
  •   feroze    15 年前

    连接可以是保持活动的连接。因此,recv()调用不会自行结束。您需要读取Content Lenght头,然后从内容中读取那么多字节。在那之后你就可以离开这个循环了。