#!/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 \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 + $interval }; $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; } } }