This client-server script does bi-directional communication.
Setup i used: The server script on windows 2003 server and the client on a linux machine.
Since i faced issues in getting the socket work, i'm posting this.
Server Side script:
Expand|Select|Wrap|Line Numbers
- #!/usr/bin/perl -w
- # serIO.pl
- # server using IO::Socket
- #---------------------
- use strict;
- use IO::Socket;
- my $port = 7890;
- my $sock = new IO::Socket::INET(
- # LocalHost => 'localhost',
- LocalPort => $port,
- Proto => 'tcp',
- Listen => SOMAXCONN,
- Reuse => 1
- ) or die "no socket :$!";
- my ($new_sock, $c_addr, $buf);
- print "Server started on port :$port\n";
- $sock->autoflush(1);
- while (($new_sock, $c_addr) = $sock->accept()) {
- print "Socket connection accepted.\n";
- my ($client_port, $c_ip) = sockaddr_in($c_addr);
- my $client_ipnum = inet_ntoa($c_ip);
- my $client_host =gethostbyaddr($c_ip, AF_INET);
- print "got a connection from: $client_host"," [$client_ipnum] ";
- print "\n";
- print $new_sock "Welcome .....\n";
- my $pid = fork();
- print "Cannot fork : $!\n" unless (defined($pid));
- if ($pid == 0) {
- while (defined ($buf = <$new_sock>)) {
- print $buf;
- print "\n";
- select(STDOUT); $| = 1;
- my $output = `$buf`;
- chomp($output);
- $output = $output . "END_OF_CMD";
- print "OUTPUT ---> $output\n";
- print $new_sock "$output\n";
- $new_sock->flush();
- }
- exit(0);
- }
- }
Client side script:
Expand|Select|Wrap|Line Numbers
- #!/usr/bin/perl -w
- # cliIO.pl
- # a simple client using IO:Socket
- #----------------
- use strict;
- use IO::Socket;
- my $host = shift || 'localhost';
- my $port = shift || 7890;
- my $sock = new IO::Socket::INET(
- PeerAddr => $host,
- PeerPort => $port,
- Proto => 'tcp',
- ) or die "no socket :$!";
- $sock->autoflush(1);
- my $ack = <$sock>;
- print "Server says: $ack\n";
- print $sock "dir\n";
- fn();
- print $sock "help\n";
- fn();
- .
- .
- .
- close $sock;
- sub fn {
- my $end_request = 1;
- while($end_request) {
- my $out = <$sock>;
- chomp($out);
- if ($out =~ /END_OF_CMD/) {
- $out =~ s/END_OF_CMD//;
- print "OUTPUT ----> $out\n";
- $end_request = 0;
- } else {
- print "OUTPUT ----> $out\n";
- }
- }
- }