DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Threads To Create A Server And Client Application In One Using Threads To Run Them

02.24.2010
| 2110 views |
  • submit to reddit
        // Threads to create a server and client application in one using Threads to run them

use warnings;
use strict;
use Frontier::Daemon;
use Frontier::Client;
use threads;
use threads::shared;

my ($nr, %threads);
my $C = {};
share($C);
print "Starting Server\/ Client\n";
&Start(qw[Server Client]);
sleep;

sub Start
{
	my @subs = @_;
	foreach my $sub (@subs)
	{
		$C->{$sub} = '1';
		$nr++;
		$threads{$nr} = threads->new(\&{$sub});
		sleep 1;
	}
}

sub Test
{
	my $time = &Timer();
	$C->{'ClientCounter'}++;
	my $Result = '#' . $C->{'ClientCounter'} . ' ' . $time . ': You\'re an asshole';
	return($Result);
}

sub Timer
{
	my ($Second, $Minute, $Hour, $Month, $Year, $WeekDay) = localtime(time);
	my $Minutes = $Minute;
	if (length($Minute) == 1) {$Minutes = '0' . $Minute}
	return("[" . $Hour . ":" . $Minutes . ":" . $Second  . "]");
}

sub Client
{
	while ($C->{'Client'} eq '1')
	{
		my $server = Frontier::Client->new( 'url' => 'http://127.0.0.1:1337/RPC2');
		my $Result = $server->call('sample.test');
		print 'Client-> ' . $Result . "\n";
	}
}

sub Server
{
	while ($C->{'Server'} eq '1')
	{
		my $methods = {'sample.test' => \&Test};
		Frontier::Daemon->new(LocalPort => 1337, methods => $methods) or die "Couldn't start HTTP server: $!";
	}
}