Reputation: 1528
This is my simple server. When I run it and telnet to it (port 5222), and have the telnet quit its connection, why isn't my on_eof function called? I.e. why isn't the string "CATASTROPHE!!!" printed?
#!/usr/bin/perl
use v5.18;
use warnings;
use EV;
use AnyEvent;
use AnyEvent::Socket;
use AnyEvent::Handle;
our $hdl;
my $server = tcp_server undef, 5222, sub {
my ($fh) = @_;
$hdl = AnyEvent::Handle->new(fh => $fh);
$hdl->on_eof(sub {
my ($handle) = @_;
say "CATASTROPHE!!!";
});
};
EV::run;
Upvotes: 3
Views: 314
Reputation: 116
tl;dr: Without trying to read from the socket, EOF cannot be detected. Use ->on_eof or ->push_read.
Long version:
The example doesn't attempt to read anything from the handle, and this is why AnyEvent::Handle doesn't attempt to read data. Without attempting to read data, it cannot detect EOF (a consequence of the POSIX API).
This behaviour is only described indirectly in the description for the start_read/stop_read methods:
Note that AnyEvent::Handle will automatically "start_read" for you when you change the "on_read" callback or push/unshift a read callback, and it will automatically "stop_read" for you when neither "on_read" is set nor there are any read requests in the queue.
The reason why it behaves like this is that, in an event-based program, there might be any amount of time between reading the data (done internally) and enqueuing a read callback. Since it is an error to receive data that isn't expected (and since not making that an error could overflow the read buffer, causing an error), there needs to be some way to avoid these errors.
Not reading data when none is requested is an automatic way of avoiding spurious errors caused by the program not being "fast enough" to process the data: AnyEvent::Handle simply doesn't read anything from the socket until the program made a decision on what to do with the data.
In your rather untypical example, you don't do anything with the socket. To get on_eof detected, you can call ->start_read, but this is unlikely to be useful in real world programs.
Upvotes: 2