Ruby TCPSocket:找出有多少数据可用
有没有办法找出 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
标准库 io/wait 在这里可能有用。要求它为基于流的 I/O(套接字和管道)提供了一些新方法,其中
准备好了吗?
。根据文档,准备好了吗?如果有可用字节而不阻塞,则返回非零。碰巧它返回的非零值是 MRI 中可用的字节数。这是一个创建一个愚蠢的小套接字服务器,然后使用客户端连接到它的示例。服务器只发送“foo”,然后关闭连接。客户端稍等一下,给服务器时间发送,然后打印有多少字节可供读取。对您来说有趣的事情是在客户端:
不要在任何实际的事情中使用该服务器代码。为了使示例简单,它故意很短。
注意:根据 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 isready?
. 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:
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.