#!/usr/bin/perl use warnings; use strict; use IO::Socket::INET; my $socket = IO::Socket::INET->new( PeerAddr => 'localhost', PeerPort => 3009, Proto => 'tcp', ) or die "Couldn't open socket: $!"; my %handler; # Register a command handler. sub registerHandler { my ($cmd, $coderef) = @_; $handler{$cmd} = $coderef; print $socket "REG $cmd\r\n"; print "Registering $cmd.\n"; } registerHandler("karma.add", \&karma_add); registerHandler("karma.subtract", \&karma_subtract); while (<$socket>) { s/\r\n$// || s/\n$//; print "Received: $_\n"; # Check that the line specifies a known command. next unless ( (my $cmd) = /^([^ \t]*)/gc ); next unless ($handler{$cmd}); (my $args) = /\G ([^\t]*)/g; my $reply = &{$handler{$cmd}}($args); # Put the reply after the second field, removing the first field. s/^([^\t]*\t)([^\t]*)/$2 $reply/ || next; print "Replying:", $_, "\n"; print $socket $_, "\n"; } sub karma_add { my $args = shift; return "Karma to $args."; } sub karma_subtract { my $args = shift; return "Karma from $args."; }