#!/usr/bin/perl
use strict;
use Event qw(loop unloop);
use Event::Watcher qw(R W T);

use IO::Socket;
use Tie::RefHash;
use encode_decode_ping;

my $port = 7676;
my $timer_event;
my $i = 1;

my $machine = "localhost";

my ($ping_msg, $ping_type);

# Listen to port.
my $server = IO::Socket::INET->new(Proto => "tcp",
				   PeerAddr => $machine,
				   PeerPort => $port)
  or die "Can't connect to : $@\n";

# initialize acceptor
my $accept_watcher = Event->io(disc => 'connect',
			       fd=>$server,
			       poll => 'r',
			       prio => 2, # normal
			       cb => \&ping_result_handler);

$ping_type = "start";
send_ping();
$ping_type = "ping";
    
# enter the main event loop
exit loop();
# end of main()

sub ping_result_handler {
  my ($e) = @_;
  my $w = $e->w;

  my  $got = $e->got;

  # print "got read \"$got\"\n";

  if ($e->got & T) {
    close $w->fd;
    $w->cancel;
    return;
  }
  if ($e->got & R) {
    my $buf='';
    my $num_bytes = sysread $w->fd, $buf, 8192;
    # print "num_bytes = $num_bytes\n";
    if (!$num_bytes) {
      print "EOF\n";
      close $w->fd;
      $w->cancel;
      $timer_event->cancel;
      return;
    }

    print "received $buf";

  }

} 

sub send_ping {
  
  $ping_msg = encode_ping($ping_type, $i++);

  print "sending \"$ping_msg\"\n";

  $ping_msg .= "\n";

  syswrite($server, 
	   $ping_msg,
	   length($ping_msg));
  
  $timer_event = Event->timer(disc => 'timeout',
			      prio => 4, # normal
			      cb => \&send_ping,
			      interval => 10,
			      repeat => 0);
  
}

