Ruby TCPSocket:找出有多少数据可用

发布于 2024-09-28 13:11:55 字数 62 浏览 0 评论 0原文

有没有办法找出 Ruby 中的 TCPSocket 上有多少字节的数据可用?即有多少字节可以准备好而不会阻塞?

Is there a way to find out how many bytes of data is available on an TCPSocket in Ruby? I.e. how many bytes can be ready without blocking?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

Smile简单爱 2024-10-05 13:11:55

标准库 io/wait 在这里可能有用。要求它为基于流的 I/O(套接字和管道)提供了一些新方法,其中准备好了吗?。根据文档,准备好了吗?如果有可用字节而不阻塞,则返回非零。碰巧它返回的非零值是 MRI 中可用的字节数。

这是一个创建一个愚蠢的小套接字服务器,然后使用客户端连接到它的示例。服务器只发送“foo”,然后关闭连接。客户端稍等一下,给服务器时间发送,然后打印有多少字节可供读取。对您来说有趣的事情是在客户端:

require 'socket'
require 'io/wait'

# Server

server_socket = TCPServer.new('localhost', 0)
port = server_socket.addr[1]
Thread.new do
  session = server_socket.accept
  sleep 0.5
  session.puts "foo"
  session.close
end

# Client

client_socket = TCPSocket.new('localhost', port)
puts client_socket.ready?    # => nil
sleep 1
puts client_socket.ready?    # => 4

不要在任何实际的事情中使用该服务器代码。为了使示例简单,它故意很短。

注意:根据 Pickaxe 书,io/wait 仅在“ioctl(2) 中的 FIONREAD 功能”(在 Linux 中)时可用。我不了解 Windows 和 Windows其他的。

The standard library io/wait might be useful here. Requiring it gives stream-based I/O (sockets and pipes) some new methods, among which is ready?. According to the documentation, ready? returns non-nil if there are bytes available without blocking. It just so happens that the non-nil value it returns it the number of bytes that are available in MRI.

Here's an example which creates a dumb little socket server, and then connects to it with a client. The server just sends "foo" and then closes the connection. The client waits a little bit to give the server time to send, and then prints how many bytes are available for reading. The interesting stuff for you is in the client:

require 'socket'
require 'io/wait'

# Server

server_socket = TCPServer.new('localhost', 0)
port = server_socket.addr[1]
Thread.new do
  session = server_socket.accept
  sleep 0.5
  session.puts "foo"
  session.close
end

# Client

client_socket = TCPSocket.new('localhost', port)
puts client_socket.ready?    # => nil
sleep 1
puts client_socket.ready?    # => 4

Don't use that server code in anything real. It's deliberately short in order to keep the example simple.

Note: According to the Pickaxe book, io/wait is only available if "FIONREAD feature in ioctl(2)", which it is in Linux. I don't know about Windows & others.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文