【问题标题】:Reading data from a socket in ruby in a multithreaded environment在多线程环境中从 ruby​​ 中的套接字读取数据
【发布时间】:2010-09-10 17:56:32
【问题描述】:

我正在尝试通过 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 的理解,如果套接字上没有等待数据,它应该什么都不返回?

【问题讨论】:

  • 这个问题写得非常糟糕,并且遗漏了一些非常重要的数据,这些数据实际上使这个问题变得有意义。代码也是错误的。请关闭它。

标签: ruby multithreading sockets


【解决方案1】:

连接可以是保持连接。因此,您的 recv() 调用不会自行结束。您将需要读取 Content-Lenght 标头,然后从内容中读取那么多字节。之后你就可以退出RECV循环了。

或者,通过设置“Connection: close”标头发出请求,以便服务器在发送响应后关闭连接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-20
    • 1970-01-01
    相关资源
    最近更新 更多