如何确定套接字读取之前可用的字节数

时间:2017-04-29 10:12:15

标签: ruby-on-rails ruby sockets

在尝试读取之前,是否可以确定可从套接字读取的字节数?

示例:

require 'socket'

client_thread = Thread.new do
  socket = nil

  begin
    socket = TCPSocket.new('localhost', 2000)
    socket.write("Hello from client")
  rescue Errno::ECONNREFUSED
    retry
  ensure
    if !socket.nil?
      if !socket.closed?
        socket.close
      end
    end
  end 
end

server = TCPServer.new('localhost', 2000)
client = server.accept

read_ready = IO.select([client], nil, nil, 30)[0]
if read_ready.include?(client)
  #There is currently 17 bytes available to read, but how do I programmatically determine this?
  data = client.recv_nonblock(17)
end

client_thread.join

0 个答案:

没有答案