perl anyevent socket编程(1)-echo client/server

前端之家收集整理的这篇文章主要介绍了perl anyevent socket编程(1)-echo client/server前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

 本来是测试coro socket server的,结果没搞定,太面了....coro::socket的文档也太简略了.

先看看anyevent的例子吧,这个出自eg中的ae2.pl

我分成了c/s两个

server代码

use warnings;
use strict;

use Time::HiRes qw(time);
use AnyEvent;
#这个是ae的perl实现,要比EV慢一点点
use AnyEvent::Impl::Perl;
use AnyEvent::Socket;
use AnyEvent::Handle;

my $CYCLES = 500;
my $port   = 11212;

#这两个都可以
my $cv = AnyEvent->condvar;
#my $cv = AE::cv;
  
tcp_server undef,$port,sub {
   my ($fh) = @_
      or die "tcp_server: $!";

   my $hdl = new AnyEvent::Handle fh => $fh;

   $hdl->push_read (line => sub {
      $hdl->push_write ("$_[1]\n");
      undef $hdl;
   });
};

#这两个都可以。。。
#$cv->wait;
$cv->recv;


client的代码

use warnings;
use strict;

use Time::HiRes qw(time);
use AnyEvent;
use AnyEvent::Impl::Perl;
use AnyEvent::Socket;
use AnyEvent::Handle;

my $CYCLES = 500;
my $port   = 11212;



my $t = time;

for my $connections (1..$CYCLES) {
   my $cv = AE::cv;

   tcp_connect "127.0.0.1",sub {
      my ($fh) = @_
         or die "tcp_connect: $!";

      my $hdl = new AnyEvent::Handle fh => $fh;

      $hdl->push_write ("can write $connections\n");
      $hdl->push_read (line => sub {
      	 my (undef,$line) = @_;
      	 print "got line $line.\n";
         undef $hdl;
         $cv->send;
      });
   };

   $cv->recv;
};

$t = time - $t;
printf "%.3f sec\n",$t;
exit;

猜你在找的Perl相关文章