in reply to EV::io and Sockets

so there must be sth. wrong with the 2nd watcher:

The one thing wrong with it is - there's no loop for it.

sub handle_incoming { my $w=shift; my $h=$w->fh; my $client=$h->accept or die; print "socket connection in...\n"; my $w = EV::io $client, EV::READ, \&handle_client; EV::loop; }

The second thing wrong is <$client> - that should be <$h>. Use strict. Use strict!

Then, in handle_client, the handler should unregister itself if the read result is undef; otherwise it will loop forever:

sub handle_client { my $w=shift; my $h=$w->fh; $in=<$h>; $w->DESTROY unless defined $in; print "in=$in\n"; }

Replies are listed 'Best First'.
Re^2: EV::io and Sockets
by Walchy (Initiate) on Jan 04, 2009 at 04:10 UTC
    Thank you very much for your help...

    The second EV::loop does work - but I don't understand why - I thought the first EV::loop starts the main loop which runs until EV::unloop is called or all watchers stopped...?

    Anyway I found the reason why handle_client isn't called in my code:
    my $w = EV::io $client, EV::READ, \&handle_client;
    because of "my" $w runs out of scope immediately and so the watcher stops. so there must be a hash or array where to store the watcher handles for every socket. The complete working code looks like this:
    use strict; use IO::Socket; use EV; my $connection_count = 0; my $h; my %h; my $server = new IO::Socket::INET ( LocalPort => 2345, Type => SOCK_STREAM, Listen => SOMAXCONN, Reuse => 1 ); my $w = EV::io $server, EV::READ, \&handle_incoming; EV::loop; sub handle_incoming { my $w=shift; my $fh=$w->fh->accept or die; $h->{$fh} = EV::io $fh, EV::READ, \&handle_client; printf "new socket connection #%d (%d)\n", ++$connection_count, +scalar keys %$h; } sub handle_client { my $c=shift; my $fh=$c->fh; my $bytes_read=sysread($fh, my $bytes, 9_999_999); return if (not exists $h->{$fh}); printf "in=%s (%d bytes)\n",$bytes,$bytes_read; if (($bytes eq 'q') || ($bytes_read == 0)) { close($fh); undef $c; # destroy event watcher delete $h->{$fh}; printf "socket connection terminated by %s (%d (%d) sockets +remaining)\n", $bytes_read == 0 ? 'peer' : 'server', --$connection_co +unt, scalar keys %$h; } }
    (Thanks and Greetings to Simon :-)

    Walchy