问题
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
回答1:
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.
来源:https://stackoverflow.com/questions/8481837/where-to-find-or-how-to-read-ruby-documentation