AnyEventのechoサーバサンプル
#!/usr/bin/perl
use AnyEvent;
use AnyEvent::Socket;
use IO::Handle;
$| = 1;
my $HOST = '192.168.1.200';
my $PORT = 9999;
tcp_server $HOST, $PORT, sub {
my ($sock, $host, $port) = @_;
autoflush $sock 1;
print "Client connected: $host($port)\n";
my $watcher; $watcher = AnyEvent->io(
fh => $sock,
poll => 'r',
cb => sub {
my $data = <$sock>;
$data =~ s/\r?\n//g;
if ($data eq 'quit') {
print "Client disconnected: $host($port)\n";
undef $watcher;
return;
}
print "$data by $host($port)\n";
print $sock "[$data]\n";
},
);
}, sub {
my ($fh, $host, $port) = @_;
print "Echo server is listening on $host($port)\n";
};
AnyEvent->condvar->recv;
WEBには、sysread、syswriteのサンプルしかないんだよね。
バッファリングされちゃうからsys*系使うんだろうけどautoflushしちゃえば良い。
PR