# A simple client/server connection class.
# Implements a generic client/server connection
# class, using POE::Wheel::ReadWrite to interact
# with the remote side of the socket.
# Copyright 2004 by Rocco Caputo.  Free software.
# Same terms as Perl itself.  Have fun!

package Connection;

use warnings;
use strict;

use POE qw(Wheel::ReadWrite);

sub spawn {
  my ($class, $socket) = @_;

  POE::Session->create(
    inline_states => {
      _start    => \&handle_start,
      got_input => \&handle_input,
      got_error => \&handle_error,
    },
    args => [ $socket ],
  );
}

sub handle_start {
  my ($heap, $socket) = @_[HEAP, ARG0];
  $heap->{stream} = POE::Wheel::ReadWrite->new(
    Handle     => $socket,
    InputEvent => "got_input",
    ErrorEvent => "got_error",
  );
}

sub handle_input {
  my ($heap, $input) = @_[HEAP, ARG0];
  $heap->{stream}->put("Got: $input");
}

sub handle_error {
  my $heap = $_[HEAP];
  my ($syscall, $errno, $text) = @_[ARG0..ARG2];
  delete $heap->{stream};
  return unless $errno;
  warn "Conn: $syscall error $errno: $text\n";
}

1;
