Ruby TCPSocket doesn't notice it when server is killed

Posted by user303308 on Stack Overflow See other posts from Stack Overflow or by user303308
Published on 2010-03-27T19:34:35Z Indexed on 2010/03/27 21:33 UTC
Read the original article Hit count: 252

Filed under:
|

I've this ruby code that connects to a TCP server (namely, netcat). It loops 20 times, and sends "ABCD ". If I kill netcat, it takes TWO iterations of the loop for an exception to be triggered. On the first loop after netcat is killed, no exception is triggered, and "send" reports that 5 bytes have been correctly written... Which in the end is not true, since of course the server never received them.

Is there a way to work around this issue ? Right now I'm losing data : since I think it's been correctly transfered, I'm not replaying it.

#!/usr/bin/env ruby
require 'rubygems'
require 'socket'

sock = TCPSocket.new('192.168.0.10', 5443)
sock.sync = true

20.times do
  sleep 2
  begin
    count = sock.write("ABCD ")
    puts "Wrote #{count} bytes"
  rescue Exception => myException
    puts "Exception rescued : #{myException}"
  end
end

© Stack Overflow or respective owner

Related posts about ruby

Related posts about sockets