files/perl/server.txt

Plain text | Download

  1.  
  2. sub listen {
  3.     my $self   = shift;
  4.     my $server = $self->create_localsocket;
  5.     my $select = IO::Select->new($server);
  6.     my(%buf, %timestamp);
  7.  
  8.     LISTEN:
  9.     while(1) {
  10.  
  11.         CHECK_TIMEOUT:
  12.         for($select->handles) {
  13.             next CHECK_TIMEOUT if($_ == $server);
  14.             if($timestamp{$_} < time - $self->Timeout) {
  15.                 delete $buf{$_};
  16.                 $select->remove($_);
  17.                 $_->close;
  18.             }
  19.         }
  20.  
  21.         CONNECTION:
  22.         for my $conn (@_ = $select->can_read(1)) {
  23.  
  24.             ### client
  25.             if($conn != $server) {
  26.  
  27.                 ### get input
  28.                 my $input;
  29.                 my $recv     = $conn->sysread($input, 1024, 0);
  30.                 $buf{$conn} .= $input;
  31.  
  32.                 ### EOT
  33.                 unless(defined $recv and length $input) {
  34.                     $timestamp{$conn} = -1;
  35.                     next CONNECTION;
  36.                 }
  37.  
  38.                 ### communicate
  39.                 if($self->communicate(\$buf{$conn})) {
  40.                     $timestamp{$conn} = time;
  41.                 }
  42.                 else {
  43.                     $timestamp{$conn} = -1;
  44.                     next CONNECTION;
  45.                 }
  46.             }
  47.  
  48.             ### server
  49.             else {
  50.  
  51.                 ### get new client
  52.                 $conn             = $server->accept;
  53.                 $timestamp{$conn} = time;
  54.                 $select->add($conn);
  55.             }
  56.         }
  57.  
  58.         ### fix timestamp
  59.         %timestamp = map { $_ => $timestamp{$_} } $select->handles;
  60.     }
  61.  
  62.     $server->shutdown(2);
  63.     exit 0;
  64. }