I see two issues with your code: First, you're not giving a timeout to the select (or rather, IO::Select) call, which is what you would need to do to implement the 10-second interval. Second, you've got the code for the heartbeat inside the loop over @$new_readable, however, if the select call times out, that variable will be undefined - please see those two documentation links for details. You will need to move the heartbeat code out of the loop, and detect timeout by setting and checking $! as described in the IO::Select docs.

Note that at the moment, your code does not cover a lot of the cases of select-based server code (e.g. errors or even the clients sending data). If you are still getting to that, great, I think that writing a complete server with select is a great learning experience for how things work on a relatively low level. OTOH, IMHO nowadays using an event loop is my personal favorite way to go, and at the moment, my favorite event loop is Mojo::IOLoop. I even wrote an example server and client and posted them here. A heartbeat can be implemented using Mojo::IOLoop->recurring.


In reply to Re: How do I make a tcp socket heartbeat? by haukex
in thread How do I make a tcp socket heartbeat? by pudda

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.