- #!/usr/bin/perl -w
-
#
-
use strict;
-
use IO::Handle;
-
use Socket;
-
-
my ($bytes_out, $bytes_in) = (0,0);
-
-
my $host = shift || 'localhost';
-
my $port = shift || getservbyname('echo', 'tcp');
-
-
my $protocol = getprotobyname('tcp');
-
-
socket(SOCK, AF_INET, SOCK_STREAM, $protocol) or die 'sock() failed: $!';
-
my $packed_add = inet_aton($host);
-
my $dest_add = sockaddr_in($port, $packed_add);
-
-
connect(SOCK, $dest_add) or die "connet() failed: $!";
-
-
SOCK->autoflush(1);
-
-
while( 1 ){
-
print "Client:";
-
my $msg_out = <>;
-
#print SOCK "Client:".$msg_out;
-
send(SOCK, "Client:".$msg_out, 0);
-
my $msg_in = <SOCK>;
-
print $msg_in;
-
-
$bytes_out += length($msg_out);
-
#$bytes_in += length($msg_in);
-
-
}
-
-
close SOCK;
-
#print STDERR "bytes_sent = $bytes_out, bytes_received = $bytes_in\n";
server:
- #!/usr/bin/perl -w
-
#
-
use strict;
-
use Socket;
-
use IO::Handle;
-
-
my ($bytes_in, $bytes_out) = (0, 0);
-
my $port = shift || '3000';
-
my $protocol = getprotobyname('tcp');
-
-
socket(SOCK, AF_INET, SOCK_STREAM, $protocol) or die "socket() failed:$!";
-
setsockopt(SOCK, SOL_SOCKET, SO_REUSEADDR, 1) or die " canot set so_reuseadd:$!";
-
-
my $my_addr = sockaddr_in($port, INADDR_ANY);
-
bind(SOCK, $my_addr) or die"bind() failed: $!";
-
listen(SOCK, SOMAXCONN) or die "listen() failed: $!";
-
-
warn "waiting for incoming connections on port $port ...\n";
-
-
while(1){
-
next unless my $remote_addr = accept(SESSION, SOCK);
-
my ($port, $hisaddr) = sockaddr_in($remote_addr);
-
warn "Connection from [", inet_ntoa($hisaddr), ", $port]\n";
-
-
SESSION->autoflush(1);
-
while(<SESSION>){
-
$bytes_in += length($_);
-
chomp;
-
print $_."\n";
-
-
#my $msg_out = (scalar reverse $_) . "\n";
-
print "Server:";
-
my $msg_out = <>;
-
print SESSION "Server:".$msg_out;
-
$bytes_out += length($msg_out);
-
}
-
warn " Connection from [", inet_ntoa($hisaddr), ", $port] finished\n";
-
close SESSION;
-
-
}
-
-
close SOCK;
阅读(142898) | 评论(0) | 转发(0) |