From: Brian Candler Date: 2010-01-12T22:12:10+09:00 Subject: Re: How to close a TCP socket? (TCPSocket#close doesn't close it) I単aki Baz Castillo wrote: > But in this case when calling socket.close the connection is not > terminated. A > simplified code: > > require "socket" > @socket = TCPSocket.new(server, port) > > Thread.new do > res = @socket.gets("\r\n") > end > > @socket.close > sleep 120 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. 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 Anyway, going back to your original code: to isolate the behaviour you've seen, I suggest you set up a ruby server and client pair of processes and connect between them (preferably using localhost). This makes it completely standalone and easy to reproduce by others, and potentially easy to fix if it is in fact a bug. Post your ruby version and platform too. Regards, Brian. -- Posted via http://www.ruby-forum.com/.