anyevent::socket+anyevent::handle server编程 (echo server改造 + 测试server)


push_read是一次性的读.

改为on_read方法可以实现持续读.直到客户端断开

#!/bin/env perl
#使用on_read代替push_read
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;
   $hdl = new AnyEvent::Handle fh => $fh,
   					on_error => sub {
               #AE::log error => $_[2];
               $_[0]->destroy;
            },
            on_eof => sub {
               $hdl->destroy; # destroy handle
               #AE::log info => "Done.";
            };
            
    $hdl->on_read (sub {
    	my ($h)=@_;
    	my $line=$h->rbuf;
      print "got a line $line.";
       $h->push_write ("$line");
      $_[0]->rbuf = "";
      #undef $hdl;
   });

            
};

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


这个稍微改改就可以配合前面的client测试了

 

#!/bin/env perl
#sever AnyEvent::Socket版
use strict;
use IO::Socket::INET;
use AnyEvent;
#这个是ae的perl实现,要比EV慢一点点
use AnyEvent::Impl::Perl;
use AnyEvent::Socket;
use AnyEvent::Handle;



my $cv = AnyEvent->condvar;


AnyEvent::Socket::tcp_server undef, 1234, sub {
   my ($fh, $host, $port) = @_;
   #print "Got new client connection: $host:$port\n";

   my $hdl; #这个定义很关键
   $hdl = new AnyEvent::Handle fh => $fh,
   					on_error => sub {
               #AE::log error => $_[2];
               $_[0]->destroy;
            },
            on_eof => sub {
               $hdl->destroy; # destroy handle
               #AE::log info => "Done.";
            };


    $hdl->on_read (sub {
    	my ($h)=@_;
    	my $line=$h->rbuf;
    	print $h->fh->fileno, ":", $line, " ";
      #print "got a line $line.";
       #$h->push_write ("$line");
      $_[0]->rbuf = "";
      #undef $hdl;
   });
   
#   $hdl->on_read (sub {
#     my ($hdl) = @_;				
#  	 print $hdl->fh->fileno, ":", $hdl->rbuf, " ";
#     $hdl->rbuf = "";
#   });
};

#$cv->wait;
$cv->recv;


说明,anyevent::socket先对coro::socket来说要多得多了,而且也有了一些例子

不过摸索过程中也出了很多状况

可能和当时人的精神状态有关

怎么也调不过

等过一天重新写一遍,可能就好了.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值