Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

I'm glad you have a working solution using one of the async libs, because that's the way it should be done. However, here's a semi-tested version using just IO::Socket and IO::Select as an example of one way it could have been done.

#!/usr/bin/perl use strict; # https://perlmonks.org/?node_id=11122630 use warnings; use IO::Socket; use IO::Select; my $port = 5000; my $hello = "Hello <VERSION>\n"; my $interval = 10; my $heartbeat = "HeartBeat\n"; my $listen = IO::Socket::INET->new( LocalPort => $port, Listen => 10, Reuse => 1, ) or die $@; my $sel = IO::Select->new($listen); my %clients; while( 1 ) { for my $fh ( $sel->can_read(1) ) { if( $fh == $listen ) { my $client = $listen->accept; $clients{$client} = { client => $client, heartbeat => time + $in +terval }; $sel->add( $client ); print $client $hello; } elsif( sysread $fh, my $buf, 4096 ) { print "got: $buf"; } else { $sel->remove( $fh ); delete $clients{ $fh }; } } for my $ref ( values %clients ) { if( time >= $ref->{heartbeat} ) { print { $ref->{client} } $heartbeat; $ref->{heartbeat} = time + $interval; } } }

I tested it with multiple telnets as clients and it happily heartbeats away, even with clients coming and going...


In reply to Re: How do I make a tcp socket heartbeat? by tybalt89
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":



  • Are you posting in the right place? Check out Where do I post X? to know for sure.
  • Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
    <code> <a> <b> <big> <blockquote> <br /> <dd> <dl> <dt> <em> <font> <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <nbsp> <ol> <p> <small> <strike> <strong> <sub> <sup> <table> <td> <th> <tr> <tt> <u> <ul>
  • Snippets of code should be wrapped in <code> tags not <pre> tags. In fact, <pre> tags should generally be avoided. If they must be used, extreme care should be taken to ensure that their contents do not have long lines (<70 chars), in order to prevent horizontal scrolling (and possible janitor intervention).
  • Want more info? How to link or How to display code and escape characters are good places to start.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (5)
As of 2024-04-16 22:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found