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

来源:互联网 发布:配置apache 编辑:程序博客网 时间:2024/06/08 05:11


push_read是一次性的读.

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

#!/bin/env perl#使用on_read代替push_readuse 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来说要多得多了,而且也有了一些例子

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

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

怎么也调不过

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

原创粉丝点击