# Encapsulate the Renoir IPC mechanism in a Perl module.
# Currently supports sending only.
#

package RenoirSocket;

use IO::Socket;

sub new {
# Open a connection to Renoir.
   my $envName = "HDS_PORT";
   if (!defined($ENV{$envName}) && defined($ENV{RENOIR_PORT})) {
      # Use old style name if necessary.
      $envName = "RENOIR_PORT";
   }
   my $envValue = $ENV{$envName};
   defined($envValue) or die "$envName is not in the environment";
   my ($host,$port) = split /:/,$envValue;
   $sock = new IO::Socket::INET(PeerAddr => $host,
                                PeerPort => $port,
                                Proto => 'tcp');
   if (!$sock) {
      die "Cannot connect to HDS";
   }
   my $object = { "socket" => $sock };
   bless $object;
   return $object;
}

sub send {
# Send a message to Renoir.
# Usage: $sock->send("text of message");
# or $sock->send("text","of","message");

   my ($object) = $_[0]; shift;
   my $msg = "a@_";
   my $msgLen = length $msg;
   my $fullMsg = "#$msgLen;$msg";
   my $sock = $object->{'socket'};
   print $sock $fullMsg;
}

sub DESTROY {
   my ($object) = @_;
   close $object->{'socket'};
}

1;
