Search notes:

echo server and client with Perl module IO::Socket

The following two scripts is a simple demonstration of using IO::Socket for a server and a client.
echo-server.pl just listens on port 2808. When a client connects to that port, the script will return whatever it receives from the client back to the client, with a prepended OK.
echo-client.pl connects to the server. Whenever the user types something on the console (STDIN), it forwards it to the server and then prints the server's answer.

echo-server.pl

use warnings; use strict;

use IO::Socket::INET;
use threads;

my $port_listen = 2808;

$| = 1; # Autoflush

my $socket = IO::Socket::INET->new(

  LocalHost   => '0.0.0.0',
  LocalPort   =>  $port_listen,
  Proto       => 'tcp',
  Listen      =>  5,
  Reuse       =>  1

) or die "Cannot create socket";

print "Waiting for tcp connect to connet on port $port_listen (see echo-client.pl)\n";

while (1) {


    my $client_socket = $socket->accept();

    my $client_address = $client_socket->peerhost;
    my $client_port    = $client_socket->peerport;

    print "$client_address $client_port has connected\n";

    threads -> create(\&connection, $client_socket);

}

$socket -> close;

sub connection {

  my $client_socket = shift;

  while (1) {

    my $data = <$client_socket>;

    return if $data eq "";

    print $client_socket "Ok $data";
  }
}
Github repository PerlModules, path: /IO/Socket/echo-server.pl

echo-client.pl

use warnings; use strict;

$| = 1; # Autoflush

use IO::Socket;
use IO::Select;

my $socket = IO::Socket::INET->new(
                 PeerAddr    => 'localhost',
                 PeerPort    =>  2808,
                 Proto       => 'tcp',
                 Timeout     =>  1
             )
             or die "Could not connect";


my $select = IO::Select->new();

$select -> add (\*STDIN);  # Does not work on Windows! [ http://stackoverflow.com/a/1701458/180275 ]
$select -> add ($socket);

while (1) {
  while (my @ready = $select -> can_read) {

    foreach my $fh (@ready) {

       if ($fh == $socket) {
          my $buf = <$socket>;
          print $buf;
       }
       else {

         my $buf = <STDIN>;
         print $socket $buf

       }
    }
  }
  print "$!\n";
}
Github repository PerlModules, path: /IO/Socket/echo-client.pl

See also

IO::Socket
Perl modules

Index