#!/usr/bin/perl -w 

use JSON;
use IO::Handle qw(autoflush);
use IO::Socket::INET;
use IO::Select;

my ($data, $msg, $reply, @ready);

$SIG{ALRM} = sub { die "alarm after 10 seconds\n"; };

alarm(10);

my $select = IO::Select->new();
my $json   = JSON->new->utf8;

my $listen = IO::Socket::INET->new(
	LocalPort => 9876,
	Proto     => 'tcp',
	Listen    => 1,
) or die "Can't bind: $@\n";

$client = $listen->accept()
	or die "Can't accept a connection: $@\n";
$client->autoflush(1);

$select->add($client);
while (@ready = $select->can_read())
{
	$ready[0]->recv($data, 2048);
	$msg = $json->decode($data);
	$ready[0]->send($json->encode([$msg->[0], "Server got: $msg->[1]"]));
}
