Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: How do I make a tcp socket heartbeat?

by tybalt89 (Prior)
on Oct 09, 2020 at 21:00 UTC ( #11122646=note: print w/replies, xml ) Need Help??


in reply to How do I make a tcp socket heartbeat?

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...

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11122646]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (2)
As of 2021-02-27 03:49 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?