baxy77bax has asked for the wisdom of the Perl Monks concerning the following question:
i am playing with sockets these days and what i would like to do is to create a super client that will be able to tell the server to send some information to all connected clients.
------------------------------------------ server ------------------------------------------ #!/usr/bin/perl -w use strict; use IO::Socket; my $PORT = $ARGV[0]; my $server = IO::Socket::INET->new( Proto => 'tcp', LocalPort => $PORT, Listen => SOMAXCONN, Reuse => 1); die "can't setup server" unless $server; my $lock = 0; my @clients = (); while (my $client = $server->accept()) { $client->autoflush(1); my $address = $client->peerhost . ":" . $client->peerport; push(@clients,$client); printf "[Connect from ". $client->peerhost . ":" . $client->peerpor +t . "]\n" ; # clients address #my @exe_array = (); _thread (sub { while ( <$client>) { next unless /\S/; if (/exe03/i){ $lock = 1; } elsif (/exe0555/){ $lock = 0; } elsif (/pri/i){ # push (@exe_array, $_); print $client "$lock\n"; } elsif(/sys/i){ print $client "sys"; } #this was my try but obviously it is not working it +is sending the command ++ to all clients including the admin elsif(/cont/i){ while(1){ foreach (@clients){ print $_ "$_ ++\n"; } sleep 2; } } elsif (/quit/i){ print $client "quit"; last; } } # finishe while } ); close $client; #turn off to send to all } ################################################## sub _thread { ################################################## my $coderef = shift; die "usage: _thread CODEREF \n" unless (@_ == 0 && $coderef && ref($ +coderef) eq 'CODE'); my $pid = fork(); if ($pid == 0){ return &$coderef(); exit; } # no waiting for the children } ------------------------------------------- client: ------------------------------------------- #!/usr/bin/perl use strict; use IO::Socket; my ($host, $port, $kidpid, $handle, $line); unless (@ARGV == 2) { die "usage: $0 host port" } ($host, $port) = @ARGV; $handle = IO::Socket::INET->new(Proto => "tcp", PeerAddr => $host, PeerPort => $port) or die "can't conne +ct to port $port on $host: $!"; # tcp connection to the specified hos +t and port $handle->autoflush(1); +# so output gets there right away my $bid = 0; die "can't fork: $!" unless defined($kidpid = fork()); +# split the program into two processes, identical twins if ($kidpid) { +# the if{} block runs only in the parent process while (defined ($line = <$handle>)) { +# copy the socket to standard output print STDOUT $line; } kill("TERM", $kidpid); +# send SIGTERM to child } elsif ($kidpid == 0) { +# the else{} block runs only in the child process while (defined ($line = <STDIN>)) { +# copy standard input to the socket print $handle $line; } exit; } else{ die "cannot fork !\n"; }
thank you
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: admin client
by gmargo (Hermit) on Nov 08, 2009 at 16:46 UTC | |
|
Re: admin client
by gman (Friar) on Nov 09, 2009 at 03:01 UTC |