# cat svr.pl
use strict;
use IO::Socket;
my $listen_socket = IO::Socket::INET->new(
LocalPort => 1234,
Listen => SOMAXCONN,
Proto => 'tcp',
Reuse => 1,
Timeout => 30,
);
die "can't create socket: " unless defined $listen_socket;
while ( 1 ) { # running on frontend
next unless my $sock = $listen_socket->accept;
my $peer_host = $sock->peerhost();
my $mesg = '';
while (<$sock>) {
$mesg .= $_;
}
print $sock "welcome $peer_host, just echo back:\n";
print $sock $mesg;
$sock->close or die "can't close established socket $!\n";
select(undef, undef, undef, 0.25);
}
# cat cli.pl
use strict;
use IO::Socket;
my $sock=IO::Socket::INET->new(PeerAddr => '127.0.0.1',
PeerPort => 1234,
Proto => 'tcp')
or die $@;
print $sock "hello first line\n";
print $sock "hello second line\n";
$sock->shutdown(1); # tell peer I have finished writing
print while <$sock>; # read from socket and print
$sock->close or die $!;
=========================result=======================
# perl svr.pl &
[1] 16704
# perl cli.pl
welcome 127.0.0.1, just echo back:
hello first line
hello second line
阅读(1036) | 评论(0) | 转发(0) |