Ruby TCPSocket:找出可用的数据量 [英] Ruby TCPSocket: Find out how much data is available

查看:187
本文介绍了Ruby TCPSocket:找出可用的数据量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以找出Ruby中的TCPSocket上有多少字节的数据可用? IE.可以准备多少字节而不会阻塞?

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?

推荐答案

标准库io/wait在这里可能有用.重新调用它会为基于流的I/O(套接字和管道)提供一些新方法,其中包括ready?.根据文档准备好了吗?如果有可用字节无阻塞,则返回non-nil.碰巧的是,它的non-nil值将返回MRI中可用的字节数.

The standard library io/wait might be useful here. Requring 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.

这里是一个示例,该示例创建一个笨拙的小型套接字服务器,然后通过客户端连接到该服务器.服务器只发送"foo",然后关闭连接.客户端稍等片刻,让服务器有时间发送,然后打印出可供读取的字节数.有趣的东西在客户端:

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 avaiable 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 retarded in order to keep the example simple.

注意:根据Pickaxe的书,仅当"ioctl(2)中的FIONREAD功能"时,io/wait才可用.它在Linux中.我不了解Windows&其他人.

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.

这篇关于Ruby TCPSocket:找出可用的数据量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆