package SoServ; #: one server for all clients use IO::Socket::INET; use IO::Select; my @CL = (); #: array of sock.Handles to Clients my $S; #: Socket-Server my $H; #: for IO::Select sub new { #: new Socket-Server my $me = {}; $me->{'a'} = shift; #: loc.Adddress address $me->{'p'} = shift; #: port to connect $S = IO::Socket::INET->new( LocalAddr => $me->{'a'}, LocalPort => $me->{'p'}, Proto => 'tcp', Listen => 1, Reuse => 1, Timeout => 60 ); die "Can't create SoServ ($!)\n\n" unless $S; $H = IO::Select->new(); $H->add($S); return bless $me; } #: wait for new connections sub waitNewConn { my $me = shift; #: either endless (1) or just 2 clients (0): my $withKids = shift; while (1) { # endless Loop if with Kids! # wait timeout-sec and then try again: my $newCL = $S->accept() || next; print $newCL "Hi, guy, nice meeting you\n"; $H->add($newCL); #update @CL instead of:push @CL,$newCL; @CL = $H->can_write(1); # no kid: return after 2 conn. return @CL if (@CL == 2 && !$withKids); } # while (1) } # sub sub clients { return @CL } ####### end packages ############# package main; my $addr = 'localhost'; # hard coded for now my $port = 2345; # dito my $Serv = SoServ::new( $addr,$port ); # start Server # Array of Handles to Clients derived from SoServ->@CL my @Clients = (); my $withKids = 1; # want kids or everyth. in 1 process? if ($withKids) { spawn($Serv); # kid is waiting for new Clients } else { # no kid, waiting here for new (2) Clients @Clients = $Serv->waitNewConn(0); } my $line = ''; my $f = '/home/cas/Data/sp1Min/spAdj.dta'; my $n = 9; # just 9 lines for now open(SP, "< $f") or die "can't open SP: $f: $!"; # while (defined($line = )) { print $line; # control @Clients = $Serv->clients() if ($withKids); for (@Clients) { print $_ $line; } last if (!$n--); } close(SP); exit; sub spawn { my $S = shift; my $pid; if (!defined($pid = fork)) { print "cannot fork: $!"; return; } elsif ($pid) { print " I'm the Server-Parent: pid:$pid \$\$:$$\n"; return; # I'm the parent } $S->waitNewConn(1); # yes with Kids, of course => (1) exit; } # end sub spawn