#!/usr/bin/perl # http://perlmonks.org/?node_id=1211329 use strict; use warnings; if( @ARGV ) # if any argument, it's the server, otherwise the client # ( for testing purposes :) { ### tcp server use DBI; use IO::Socket::INET; ### flush after every write $|= 1; # creating object interface of IO::Socket::INET modules which internally does # socket creation, binding and listening at the specified port address. my $socket = new IO::Socket::INET ( LocalHost=> '127.0.0.1', LocalPort=> '5000', Proto=> 'tcp', Listen=> 5, Reuse=> 1 ) or die "ERROR in Socket creation: $!\n"; print "I am waiting clients to connect on port 5000.\n"; ### infinite loop while(1) { my($client_socket); my($peeraddress, $peerport); my($row, $data); my @processes= ('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'); while($row= shift(@processes)) { $client_socket = $socket->accept(); $peeraddress = $client_socket->peerhost(); $peerport = $client_socket->peerport(); print "Sending $row to $peeraddress:$peerport)... "; # write to the newly accepted client. print $client_socket "$row\n"; # read from the newly accepted client. $data = <$client_socket> // 'nothing'; chomp($data); print "got $data from client.\n"; $client_socket->close(); } #$socket->close(); } } else { ### tcp client my $max = 2; my $active = 0; while( 1 ) { while( $active < $max ) { if( my $pid = fork ) # parent { $active++; } elsif( defined $pid ) # child { my($socket, $data); $socket= new IO::Socket::INET ( PeerHost=> '127.0.0.1', PeerPort=> '5000', Proto=> 'tcp' ) or die "ERROR in Socket creation: $!\n"; $socket->autoflush(1); $data= <$socket>; chomp($data); $socket->close(); print "($$) Got $data from producer.\n"; sleep 1; exit; } else { die "fork failed $!"; } } if( $active == $max ) { wait; $active--; } } }