问题描述
我有一些代码用于从网络套接字获取数据.它工作正常,但我通过反复试验陷入困境.我谦虚地承认我并不完全理解它是如何工作的,但我真的很想.(这是我发现的货物崇拜形式的工作代码)
I have some code that I'm using to get data from a network socket. It works fine, but I flailed my way into it through trial and error. I humbly admit that I don't fully understand how it works, but I would really like to. (This was cargo culted form working code I found)
我不明白的部分以ready = IO.select ..."开头,我不清楚:
The part I don't understand starts with "ready = IO.select ..." I'm unclear on:
- IO.select 正在做什么(我尝试查找,但对内核和其他内容更加困惑)
- IO.select 的数组参数的用途
- ready[0] 在做什么
- 读取 1024 字节的总体思路?一次
代码如下:
@mysocket = TCPSocket.new('192.168.1.1', 9761)
th = Thread.new do
while true
ready = IO.select([@mysocket])
readable = ready[0]
readable.each do |socket|
if socket == @mysocket
buf = @mysocket.recv_nonblock(1024)
if buf.length == 0
puts "The server connection is dead. Exiting."
exit
else
puts "Received a message"
end
end
end
end
end
提前感谢您帮助我学习钓鱼".我讨厌有一些我不完全理解的代码 - 这只是巧合.
Thanks in advance for helping me "learn to fish". I hate having bits of my code that I don't fully understand - it's just working by coincidence.
推荐答案
1) IO.select
接受一组套接字并等待直到可以用它们读取或写入(或者如果发生错误).它返回发生的套接字事件.
1) IO.select
takes a set of sockets and waits until it's possible to read or write with them (or if error happens). It returns sockets event happened with.
2) 数组包含检查事件的套接字.在您的情况下,您仅指定用于读取的套接字.
2) array contains sockets that are checked for events. In your case you specify only sockets for reading.
3) IO.select
返回套接字数组的数组.元素 0 包含可以读取的套接字,元素 1 - 可以写入的套接字和元素 2 - 有错误的套接字.
3) IO.select
returns an array of arrays of sockets. Element 0 contains sockets you can read from, element 1 - sockets you can write to and element 2 - sockets with errors.
获取套接字列表后,您可以读取数据.
After getting list of sockets you can read the data.
4) 是的,recv_nonblock
参数是以字节为单位的大小.请注意,实际读取的数据大小可能小于 1024,在这种情况下,您可能需要重复 select
(如果实际数据对您很重要).
4) yes, recv_nonblock
argument is size in byte. Note that size of data actually being read may be less than 1024, in this case you may need to repeat select
(if actual data matters for you).
这篇关于在 Ruby 中读取套接字时了解 IO.select的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!