title: Understanding IO.select when reading socket in Ruby
body: <p>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)</p>
  
  <p>The part I don't understand starts with "ready = IO.select ..." I'm unclear on:</p>
  
  <ol>
  <li>What IO.select is doing (I tried looking it up but got even more confused with Kernel and what-not)</li>
  <li>what the array argument to IO.select is for</li>
  <li>what ready[0] is doing</li>
  <li>the general idea of reading 1024 bytes? at a time</li>
  </ol>
  
  <p>Here's the code:</p>
  
  <pre><code>@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
  </code></pre>
  
  <p>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.</p>