IO :: EAGAINWaitReadable:资源暂时不可用 – 读取将阻止

当我尝试使用“socket”库中的“read_nonblock”方法时,我收到以下错误

IO::EAGAINWaitReadable: Resource temporarily unavailable - read would block 

但是当我通过终端上的IRB尝试它时工作正常

如何让它读取缓冲区?

当我尝试使用“socket”库中的“read_nonblock”方法时,我收到以下错误

当数据在缓冲区中没有准备好时,它是预期的行为。 由于exceptionIO::EAGAINWaitReadable源自ruby版本2.1.0 ,因此在旧版本中,您必须使用其他端口选择捕获IO::WaitReadable试。 就像在ruby文档中建议的那样:

 begin result = io.read_nonblock(maxlen) rescue IO::WaitReadable IO.select([io]) retry end 

对于较新版本的os ruby​​,您也应该捕获IO::EAGAINWaitReadable ,但只需重试读取超时或无限。 我没有在文档中找到示例,但请记住它没有端口选择:

 begin result = io.read_nonblock(maxlen) rescue IO::EAGAINWaitReadable retry end 

然而,我的一些调查导致在IO::EAGAINWaitReadable上进行端口选择也更好,所以你可以得到:

 begin result = io.read_nonblock(maxlen) rescue IO::WaitReadable, IO::EAGAINWaitReadable IO.select([io]) retry end 

为了支持两个版本的exception代码,只需在if子句下的lib / core中声明IO::EAGAINWaitReadable的定义:

 if ! ::IO.const_defined?(:EAGAINWaitReadable) class ::IO::EAGAINWaitReadable; end end