I'd recommend to use POE or AnyEvent for your program. These packages will take care about low level details, so you should only write handlers for read/write events.

Update: here's the example that uses AnyEvent. Start without arguments for server, or specify hostname as argument for client.

use strict; use warnings; use AnyEvent; use AnyEvent::Socket; use AnyEvent::Handle; my $port = 7777; my $cv = AnyEvent->condvar; if ( $ARGV[0] ) { # client tcp_connect $ARGV[0], 7777, sub { my ($fh) = @_ or die "connect failed: $!"; create_handle($fh, 1); }; } else { # server tcp_server undef, 7777, sub { my ( $fh, $host, $port ) = @_; warn "Accepted connection from $host\n"; create_handle($fh, 0); }; } sub create_handle { my ($socket, $exit_on_close) = @_; my ( $shandle, $thandle ); my $destroy = sub { $shandle->destroy; $thandle->destroy; $cv->send if $exit_on_close; }; $shandle = AnyEvent::Handle->new( fh => $socket, on_error => $destroy, on_close => $destroy, ); $thandle = AnyEvent::Handle->new( fh => \*STDIN, on_error => $destroy, on_close => $destroy, ); $shandle->on_read( sub { print $shandle->rbuf; $shandle->rbuf = ''; } ); $thandle->on_read( sub { $shandle->push_write( $thandle->rbuf ); $thandle->rbuf = ''; } ); } $cv->recv;

Update: fixed some issues


In reply to Re: Bidirectional Communication using sockets and forking by zwon
in thread Bidirectional Communication using sockets and forking by biohisham

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.