clone4 has asked for the wisdom of the Perl Monks concerning the following question:

hi monks,

Recently I started to mess around with socket programming in perl, and I've little stumped on this piece of code, which is supposed to be simple script to communicate through the socket s:
Server
use IO::Socket; $sock = IO::Socket::INET->new ( Localhost => 'localhost', LocalPort => '18080', Proto => 'tcp', Listen => 1, ); die "cant do that: $!\n" unless $sock; $new_sock = $sock->accept(); while(<$new_sock>){ $ex = $_; $response = system($ex); } close($sock);


Client
use IO::Socket; $sock = IO::Socket::INET->new ( PeerAddr => 'localhost', PeerPort => '18080', Proto => 'tcp', ); if($sock->connected){ print "Ex->"; while(chomp($in = <STDIN>)){ print $sock "$in\n"; } } close($sock);
Anyway now any valid command entered to client script will be executed by the server, but I'd need to then return what system() function returns, to the client script and print it. Second thing I wanted to do but couldn't achieve is reverse the relationship, i.e. client connects to the server and server executes commands on the client and gets the result. Any ideas would be appreciated...

Again thanks for any help

Replies are listed 'Best First'.
Re: IO::Socket server->client
by ikegami (Patriarch) on Oct 12, 2008 at 17:19 UTC

    Sockets are bidirectional, so just print out the output back to the socket. Of course, system doesn't actually return the output, so you'll need something else.

    my $client_sock = $sock->accept(); while(<$client_sock>){ chomp; print $client_sock `$_`; }

    You'll need to add some kind of system to allow the client to know when the server is done sending.

    Are you just exploring, or are you reinventing ssh?

      What you are describing is exactly what inetd/xinetd is designed for http://linux.die.net/man/8/xinetd. Of course, if you are just trying socket code out, there are numerous tutorials/examples here at the monastery.
Re: IO::Socket server->client
by Corion (Patriarch) on Oct 12, 2008 at 17:05 UTC