Ruby的select为什么不返回套接字? [英] Why doesn't Ruby's select return the socket?
问题描述
我试图在STDIN和Ruby中的TCP套接字上使用select,但是由于某些原因,从select返回的值似乎从未与选择之一匹配;看起来好像是要返回的套接字,但是使用==(或等于?)不匹配.谁能告诉我为什么select所返回的结果与我传入的对象不匹配,以及在这里我应该做些什么?
I'm trying to use select on STDIN and a TCP socket in Ruby, but for some reason, the value returned from select never seems to match one of the choices; it looks like it's the socket that's being returned, but it doesn't match using == (or equal?). Can anyone tell me why the result returned from select doesn't match the objects I passed in, and what I should be doing differently here?
server = TCPSocket::new("irc.freenode.net", 7000)
server.puts "NICK MyBot"
server.puts "USER #{ENV['USER']} 0 * :My Bot"
# <snip definitions>
while (!$done)
results = select([server, STDIN], nil, nil)
if results[0] == STDIN
puts "Reading from STDIN"
execute_command
elsif results[0] == server
puts "Reading from server"
receive_data
else
puts "Something's wrong... results[0]: #{results[0]}, server: #{server}"
puts "IDs: results[0]: #{results[0].__id__}, server: #{server.__id__}"
exit 1
end
end
这是我运行此程序后得到的:
Here's what I get when I run this:
Something's wrong... results[0]: #<TCPSocket:0x33c390>, server: #<TCPSocket:0x33c390>
IDs: results[0]: 1695840, server: 1695990
我正在Mac OS X上运行Ruby 1.8.6版.
I'm running Ruby version 1.8.6 on Mac OS X.
$ ruby --version
ruby 1.8.6 (2008-03-03 patchlevel 114) [universal-darwin9.0]
$ which ruby
/usr/bin/ruby
推荐答案
select返回的Array的第一个元素是已准备好的IO对象的Array.因此,您应该将STDIN和服务器与结果[0] [0]进行比较.或者更好地检查套接字是否在结果数组中
The fist element of the Array returned by select is an Array of the IO objects that are ready. So you should compare the STDIN and server to results[0][0]. Or better check, if the socket is in the results Array
...
if results[0].include? STDIN
...
elsif results[0].include? server
...
...
这篇关于Ruby的select为什么不返回套接字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!