From: "Iñaki Baz Castillo" Date: 2010-01-12T22:32:24+09:00 Subject: Re: How to close a TCP socket? (TCPSocket#close doesn't close it) El Martes, 12 de Enero de 2010, Brian Candler escribió: > When I run this code, substituting a 'www.google.com' and port 80, I see > the socket in TIME_WAIT state if I go to another terminal. > > This is with > ruby 1.8.6 (2007-09-24 patchlevel 111) [i486-linux] > built from source, running under Ubuntu Hardy. > > It appears to be consistent: i.e. I can ctrl-C out of the program and > start it again, and each time I get another TIME_WAIT socket. I really sorry, I was doing a "grep ESTABLISHED" in my netstat command... Of course the TIME_WAIT appears after closing the connection :) Sorry. > Whilst what you're doing is probably allowed, it's a bit ugly: one > thread is waiting to read data from a socket at the same time as another > closes it. > > There is a more graceful way which might be useful. In the writing > thread you can half-close the socket (@socket.close_write). If the other > side notices this and then closes from its side, you can then finish > reading what it sends you and close the read side. > > require "socket" > @socket = TCPSocket.new('smtp.example.com', 25) > > Thread.new do > while res = @socket.gets("\r\n") > STDERR.puts res > end > @socket.close_read > end > > @socket.close_write > sleep 120 Yes, this works much better :) Thanks a lot. -- Iñaki Baz Castillo