rb: Enhance non-blocking read in Socket

Also prevent errors when trying to close a @handle twice


git-svn-id: https://svn.apache.org/repos/asf/incubator/thrift/trunk@669010 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/lib/rb/lib/thrift/transport/socket.rb b/lib/rb/lib/thrift/transport/socket.rb
index 6b648cf..7cf2f45 100644
--- a/lib/rb/lib/thrift/transport/socket.rb
+++ b/lib/rb/lib/thrift/transport/socket.rb
@@ -48,8 +48,11 @@
         else
           data = @handle.read(sz)
         end
+      rescue Errno::EAGAIN => e
+        # let our parent know that the nonblock read failed
+        raise e
       rescue StandardError => e
-        @handle.close
+        @handle.close unless @handle.closed?
         @handle = nil
         raise TransportException.new(TransportException::NOT_OPEN, e.message)
       end
@@ -59,10 +62,18 @@
       data
     end
 
+    def read_nonblock(sz)
+      read(sz, true)
+    end
+
     def close
-      @handle.close unless @handle.nil?
+      @handle.close unless @handle.nil? or @handle.closed?
       @handle = nil
     end
+
+    def to_io
+      @handle
+    end
   end
   deprecate_class! :TSocket => Socket
 
@@ -95,7 +106,7 @@
     end
 
     def close
-     @handle.close unless @handle.nil?
+     @handle.close unless @handle.nil? or @handle.closed?
      @handle = nil
     end
   end
diff --git a/lib/rb/spec/socket_spec.rb b/lib/rb/spec/socket_spec.rb
index 4f5868b..4b6dae5 100644
--- a/lib/rb/spec/socket_spec.rb
+++ b/lib/rb/spec/socket_spec.rb
@@ -5,7 +5,7 @@
 
   before(:each) do
     @socket = Socket.new
-    @handle = mock("Handle")
+    @handle = mock("Handle", :closed? => false)
     @handle.stub!(:close)
   end
 
@@ -107,7 +107,7 @@
     end
 
     it "should close the handle when closed" do
-      handle = mock("TCPServer")
+      handle = mock("TCPServer", :closed? => false)
       TCPServer.should_receive(:new).with(nil, 1234).and_return(handle)
       @socket.listen
       handle.should_receive(:close)