I know the first part, but am not sure how to check whether tcp connection is active and how to reconnect...

That is exactly what the person who replied was trying to show you. Like Tanktalus, I am a bit fuzzy on the exact details but the code sketched out above is what you want, perhaps modulo some additional checking on what constitues a failed or absent connection. At a minimum you'll have to fill out the parameters for the new() call. And it would be good to make those details easily configurable or overrideable (config file, command line...).

Other than that, any time you need the socket, you would just have to say

my $sock = get_socket();

... anywhere in your code, and it will Just Work™. The first time, it will establish the connection and give you the associated socket. On subsequent calls it will simply hand you back the associated socket. If the connection is ever lost, the subsequent call to get_socket() will re-establish it for you.

Things to think about: what happens when the remote server is completely inaccessible, i.e., someone kicked out the network cable. How do you fail? And if it is transient, how do you deal with retries? Conventional wisdom says that three retries with an increasing delay (e.g. 1.5 seconds, 3 seconds, 4.5 seconds) is usually enough to deal with transient errors.

- another intruder with the mooring in the heart of the Perl


In reply to Re^3: Maintain TCP client connection to server? by grinder
in thread Maintain TCP client connection to server? by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.