perl Socket编程实例代码

2019-10-01 14:23:58王旭

          warn "Connection from [",inet_ntoa($hisaddr),",$port] finishedn";
          close SESSION;
          exit 0;
      }else {
          print "Forking child $pidn";
      }
}
close SOCK;

利用上述tcp_socket_cli.pl访问该server的执行结果:
[hzqbbc@local misc]$ perl tcp_socket_dt_srv.pl
Starting server on port 3000...
Connection from [127.0.0.1,32888]
Connection from [127.0.0.1,32888] finished
Reaped child 13927
Forking child 13927

TCP 客户端 ,IO::Sockiet模块
简介:同样为客户端,不过使用的是IO::Socket 面向对象模块

#!/usr/bin/perl -w
# tcp_iosocket_cli.pl
use strict;
use IO::Socket;
my $addr = $ARGV[0] || '127.0.0.1';
my $port = $ARGV[1] || '3000';
my $buf = undef;
my $sock = IO::Socket::INET->new(
        PeerAddr => $addr,
        PeerPort => $port,
        Proto    => 'tcp')
    or die "Can't connect: $!n";
$buf = <$sock>;
my $bs = length($buf);
print "Received $bs bytes, content $bufn"; # actually get $bs bytes
close $sock;

TCP 服务端, IO::Socket模块, forking/accept模型
简介:同样的一个daytime
服务器,使用IO::Socket重写。

#!/usr/bin/perl
# tcp_iosocket_dt_srv.pl
use strict;
use IO::Socket;
use POSIX qw(WNOHANG);
$SIG = sub {
     while((my $pid = waitpid(-1, WNOHANG)) >0) {
          print "Reaped child $pidn";
      }
};
my $port     = $ARGV[0] || '3000';
my $sock = IO::Socket::INET->new( Listen    => 20,
                                  LocalPort => $port,
                                  Timeout   => 60*1,
                                  Reuse     => 1)
  or die "Can't create listening socket: $!n";
warn "Starting server on port $port...n";
while (1) {
     next unless my $session = $sock->accept;
     defined (my $pid = fork) or die "Can't fork: $!n";