2
0

server.pl 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/perl
  2. use strict;
  3. use warnings;
  4. use IO::Socket::INET;
  5. use lib "..";
  6. use Tpl;
  7. $SIG{CHLD} = "IGNORE"; # don't create zombies
  8. our $port = 2000;
  9. sub handle_client {
  10. my $client = shift;
  11. undef $/;
  12. my $request = <$client>; # get request (slurp)
  13. # read input array, and calculate total
  14. my ($i,$total);
  15. my $tpl = Tpl->tpl_map("A(i)", \$i);
  16. eval { $tpl->tpl_load(\$request); };
  17. die "received invalid tpl" if $@;
  18. $total += $i while $tpl->tpl_unpack(1) > 0;
  19. # formulate response and send
  20. my $tpl2 = Tpl->tpl_map("i", \$total);
  21. $tpl2->tpl_pack(0);
  22. my $response = $tpl2->tpl_dump();
  23. print $client $response;
  24. close $client;
  25. }
  26. my $server = IO::Socket::INET->new(LocalPort => $port,
  27. Type => SOCK_STREAM,
  28. Reuse => 1,
  29. Listen => 10 )
  30. or die "Can't listen on port $port: $!\n";
  31. while (1) {
  32. my $client = $server->accept();
  33. next unless $client;
  34. # new connection
  35. my $pid = fork;
  36. die "can't fork: $!\n" unless defined $pid;
  37. if ($pid > 0) {
  38. #p arent
  39. close $client;
  40. } elsif ($pid == 0) {
  41. # child
  42. handle_client($client);
  43. exit(0);
  44. }
  45. }
  46. close ($server);