On Wed, Jun 10, 2009 at 01:40, Octavian Rasnita<orasn...@gmail.com> wrote:
snip
> IO::Socket::INET doesn't give too many details about the methods it
> supports, and I need to also study IO::Socket, and Socket and finally many
> other built in perl functions or perlipc. I will study them, but I told I
> was searching for a higher level module because I am sure I will need just a
> few methods from all those offered by IO::Socket::INET.
snip

Here is a sample client and server.  The server expects 9 bytes that
tell it how many bytes to expect in the second part, a message, and a
trailer that consists of "123456789".  The server then sends back
information about the message.

The client sends the expected information and then reads the message
the server sends back.

Server code:

#!/usr/bin/perl

use strict;
use warnings;

use IO::Socket;
use File::Basename;
use Cwd qw(realpath);

my $home = dirname realpath $0;

my $server = IO::Socket::INET->new (
        LocalHost => '127.0.0.1',
        LocalPort => '7777',
        Proto     => 'tcp',
        Listen    => SOMAXCONN,
        Reuse     => 1,
) or die "Could not create socket: $!\n";

while (my ($sock, $addr) = $server->accept){
        my ($port, $ip) = sockaddr_in $addr;
        my $ipnum       = inet_ntoa   $ip;

        print "\n\nServer connected with  a client from: [$ipnum] \n";

        my $header_bytes = sysread $sock, my $header, 9;

        unless ($header_bytes == 9) {
                warn "bad header: [$header]\n";
                next;
        }

        my $body_bytes = sysread $sock, my($body), $header;

        unless ($body_bytes == $header) {
                warn "bad body: [$body]\n";
                next;
        }

        my $trailer_bytes = sysread $sock, my $trailer, 9;

        unless ($trailer_bytes == 9) {
                warn "bad trailer: [$trailer]\n";
                next;
        }

        unless ($trailer eq '123456789') {
                warn "invalid trailer: [$trailer]\n";
                next;
        }

        my $count =()= $body =~ /(\w+)/g;

        print $sock
                "length: ", length $body, "\n",
                "word count: $count\n";
}

Client code:

#!/usr/bin/perl

use strict;
use warnings;

use IO::Socket;

my $sock = IO::Socket::INET->new(
        Proto    => "tcp",
        PeerAddr => "localhost",
        PeerPort => "7777",
) or die "Could not create socket: $!\n";

my $message = "I am a little teapot";
my $header  = sprintf "%09d", length $message;
my $trailer = "123456789";

print $sock "$header$message$trailer";

#read bytes form the server until it closes the connection
my $buf;
while (sysread $sock, my $char, 1) {
        $buf .= $char;
}

print $buf;



-- 
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.

-- 
To unsubscribe, e-mail: beginners-unsubscr...@perl.org
For additional commands, e-mail: beginners-h...@perl.org
http://learn.perl.org/


Reply via email to