#!/usr/bin/perl
use strict;
use CGI;	# or any other CGI:: form handler/decoder
use CGI::Ajax;
use IO::Socket;

my $cgi = new CGI;
my $pjx = new CGI::Ajax( 'ajax_magic' => \&resp );
$| = 1; # always flush immediately

print $pjx->build_html($cgi, \&init);

sub resp {
  my $sock = new IO::Socket::INET(PeerAddr => 'localhost', PeerPort => '5555', Proto => 'tcp');
  print $sock "resp\n";
  print STDERR join(":", @_);
  print $sock join(":", @_), ":END:";
  my $output;
  while(<$sock>) {
	last if($_ =~ "END");
	$output .= $_;
  }
  return $output;
}

sub init {
  my $sock = new IO::Socket::INET(PeerAddr => 'localhost', PeerPort => '5555', Proto => 'tcp');
  my $html;
  print $sock "init\n";
  my $output;
  while(<$sock>) {
	last if($_ =~ "END");
	$output .= $_;
  }
  return $output;
}
