jmls
jmls

Reputation: 2969

reconnect tcpsocket (or how to detect closed socket)

I have a ruby tcpsocket client that is connected to a server.

How can I check to see if the socket is connected before I send the data ?

Do I try to "rescue" a disconnected tcpsocket, reconnect and then resend ? if so, does anyone have a simple code sample as I don't know where to begin :(

I was quite proud that I managed to get a persistent connected client tcpsocket in rails. Then the server decided to kill the client and it all fell apart ;)

edit

I've used this code to get round some of the problems - it will try to reconnect if not connected, but won't handle the case if the server is down (it will keep retrying). Is this the start of the right approach ? Thanks

def self.write(data)
  begin
    @@my_connection.write(data)
  rescue Exception => e  
    @@my_connection = TCPSocket.new 'localhost', 8192
    retry
  end
end

Upvotes: 7

Views: 1460

Answers (1)

J M
J M

Reputation: 203

What I usually do in these types of scenarios is keep track of consecutive retries in a variable and have some other variable that sets the retry roof. Once we hit the roof, throw some type of exception that indicates there is a network or server problem. You'll want to reset the retry count variable on success of course.

Upvotes: 1

Related Questions