1

Running through some examples about sockets, one I've come across is this one and I'm struggling with the syntax a bit. Here's the code, it works just fine;

require "socket"

server = TCPServer.new(1234)

loop do
  Thread.start(server.accept) do
    |connection|
    puts "Connection started"
    while line = connection.gets
      break if line =~ /quit/ 
      puts line
      connection.puts "received"
    end

    conneciton.puts "closing the connection"
    connection.close
  end    
end

After a little head scratching I figured out that the server.accept code would wait until a connection is detected before starting a thread that loops until quit is called, then closes it.

What I would like a little help with is how I was supposed to have inferred this from the documentation without noodling around with the code? Am I looking in the wrong place for documentation or is it there in plain sight and I'm just not reading it correctly? Here's the source I've been using;

http://www.ruby-doc.org/stdlib-1.9.2/libdoc/socket/rdoc/TCPServer.html#method-i-accept

Mikey Hogarth
  • 4,672
  • 7
  • 28
  • 44
  • 1
    That is the official location for source. The Internet and books written by experienced developers are a good additional source of tutorials and documentation on both trivial and non-trivial concepts. – Phrogz Dec 12 '11 at 23:09
  • The code highlighting seems to be a bit borked in that `TCPServer.open(“127.0.0.1”, 14641) {|serv|` lacks a grey background. – Andrew Grimm Dec 12 '11 at 23:28

1 Answers1

3

The truth is, that documentation could be better.

That documentation assumes you're familiar with sockets already—that's a very similar (maybe even identical) behavior to the POSIX accept call, whose documentation states that if they're aren't pending connections and you didn't explicitly request non-blocking operation "accept() shall block until a connection is present". ("Block" is UNIX-speak for a particular type of waiting).

Non-blocking operation in the Ruby class is accept_nonblock (according to the document you linked), so you can infer accept is blocking.

The Ruby documentation is maintained by volunteers, and I'm sure they'd be happy to accept patches to make it better.

derobert
  • 49,731
  • 15
  • 94
  • 124