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; my $port = 7890; my $proto = getprotobyname('tcp'); my $now ; my $verbose =1; $|++; my $server = new IO::Socket::INET ( LocalHost => '1.2.3.4', 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 =~ /SpecialCommand\s{1}?(.*)/ ) { $now = time; $verbose && print STDOUT "$now RECV command Special Command arg: $1\n"; $verbose && print STDOUT "$now SEND OK: Special Command Result\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 => -$$; }