1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
# Server Program
use strict;
use IO::Socket::INET;
use JSON;
print ">> Server Program <<\n";
$| = 1;
$SIG{CHLD} = sub {wait ()}; # avoid zombies
my $serverPort = 1234;
# Create the socket
my $server = IO::Socket::INET->new (
Proto => 'tcp',
LocalPort => $serverPort,
Listen => 5,
Reuse => 1
) or die "Could not create socket! Reason: $!.\n";
print "> Server is waiting for clients!\n";
while (my $client = $server->accept())
{
# Fork process to handle multiple clients
my $pid = fork();
if ($pid == 0)
{
print ">New client!";
# Read the request from client
my $req = '';
while(1)
{
recv($client, my $packet, 100, 0);
print "\n" . 'read > ' . $packet;
$req = $req . $packet;
last if ($req =~ m/\n/);
}
# Input data deserialization
$req = from_json($req);
print ">Request:\n" . Dumper($req);
#
# Process some OLE
#
# Response serialization
my $res = to_json($req);
# Send results to client
print ">Start sending response to client!\n";
while ((length($res) % 100) != 0)
{
print 'write > ' . substr($res, 0, 100) . "\n";
print $client substr($res, 0, 100, '');
}
print $client "\n";
print ">Response sent!\n";
exit(0); # Child process exits when it is done.
} # else it's the parent process, which goes back to accept()
}
close ($server);
exit; |
Partager