Perl Notes/IO::Socket::INET client server
From Federal Burro of Information
Jump to navigationJump to search
client
server#!/usr/bin/perl -w use strict; use IO::Socket; require "/usr/local/perl/security/initdb2.pl"; require "/usr/local/perl/common/common2.pl"; require "/usr/local/perl/common/common-rrd2.pl"; my $port = 7890; my $proto = getprotobyname('tcp'); my $now ; my $verbose =1; $|++; my $server = new IO::Socket::INET ( LocalHost => '172.22.22.34', LocalPort => $port, Proto => $proto, Listen => 10, Reuse => 1, ); die "Could not create server socket: $!\n" unless $server; sub myexit { my $sig = shift; print STDOUT time . " $$ Caught $sig on server side\n" ; # close($server); }; sub Wait { print STDOUT time . " Wait called (SIG CHLD signal)\n"; wait; #wait needed to keep <defunct> pids from building up } $SIG{CHLD} = \&Wait; $SIG{QUIT} = \&myexit; $SIG{INT} = \&myexit; $verbose && print time . " Server Socket created\n"; my $client; while ( $client = $server->accept()) { $verbose && print time ." Accepted socket\n"; next if my $pid = fork; die "fork - $!\n" unless defined $pid; $verbose && print time . " Forked!\n"; $verbose && print STDOUT time . " Child Closing Server\n"; # close ( $server ); select $client; $now = time; $verbose && print "$now child selected\n"; while(my $line = <$client>) { chomp $line; if ( $line =~ /QUIT/ ) { $now = time; $verbose && print STDOUT "$now RECV QUIT command, QUITING\n"; next; } elsif ( $line =~ /ShowGraph\s{1}?(.*)/ ) { $now = time; $verbose && print STDOUT "$now RECV command ShowGraph arg: $1\n"; # ShowGraph 0:56:3:0:ScanQueue:Scan Queue Length:average $verbose && print STDOUT "$now SEND OK: Showgraph\n"; $verbose && print $client "OK: Showgraph\n"; } else { $verbose && print STDOUT "$now RECV Unrecognized command: $line\n"; $verbose && print $client "ERROR: Unrecognized command\n"; } } $verbose && print STDOUT time . " child closing client\n"; close ($client); exit(0); } continue { $verbose && print STDOUT time . " Parent Continue, closing client\n"; close($client); $verbose && print STDOUT time . " Parent client closed, sending CHLD to children\n"; kill CHLD => -$$; }