Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 957
jmls Avatar asked Sep 28 '12 18:09

jmls


1 Answers

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.

like image 96
Joe McDonagh Avatar answered Oct 03 '22 17:10

Joe McDonagh