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
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |