… | |
… | |
1511 | } |
1511 | } |
1512 | } |
1512 | } |
1513 | |
1513 | |
1514 | =back |
1514 | =back |
1515 | |
1515 | |
|
|
1516 | |
|
|
1517 | =head1 NONFREQUENTLY ASKED QUESTIONS |
|
|
1518 | |
|
|
1519 | =over 4 |
|
|
1520 | |
|
|
1521 | =item How do I read data until the other side closes the connection? |
|
|
1522 | |
|
|
1523 | If you just want to read your data into a perl scalar, the easiest way to achieve this is |
|
|
1524 | by setting an C<on_read> callback that does nothing, clearing the C<on_eof> callback |
|
|
1525 | and in the C<on_error> callback, the data will be in C<$_[0]{rbuf}>: |
|
|
1526 | |
|
|
1527 | $handle->on_read (sub { }); |
|
|
1528 | $handle->on_eof (undef); |
|
|
1529 | $handle->on_error (sub { |
|
|
1530 | my $data = delete $_[0]{rbuf}; |
|
|
1531 | undef $handle; |
|
|
1532 | }); |
|
|
1533 | |
|
|
1534 | The reason to use C<on_error> is that TCP connections, due to latencies |
|
|
1535 | and packets loss, might get closed quite violently with an error, when in |
|
|
1536 | fact, all data has been received. |
|
|
1537 | |
|
|
1538 | It is usually better to use acknowledgements when transfering data, |
|
|
1539 | to make sure the other side hasn't just died and you got the data |
|
|
1540 | intact. This is also one reason why so many internet protocols have an |
|
|
1541 | explicit QUIT command. |
|
|
1542 | |
|
|
1543 | |
|
|
1544 | =item I don't want to destroy the handle too early - how do I wait until all data has been sent? |
|
|
1545 | |
|
|
1546 | After writing your last bits of data, set the C<on_drain> callback |
|
|
1547 | and destroy the handle in there - with the default setting of |
|
|
1548 | C<low_water_mark> this will be called precisely when all data has been |
|
|
1549 | written to the socket: |
|
|
1550 | |
|
|
1551 | $handle->push_write (...); |
|
|
1552 | $handle->on_drain (sub { |
|
|
1553 | warn "all data submitted to the kernel\n"; |
|
|
1554 | undef $handle; |
|
|
1555 | }); |
|
|
1556 | |
|
|
1557 | =back |
|
|
1558 | |
|
|
1559 | |
1516 | =head1 SUBCLASSING AnyEvent::Handle |
1560 | =head1 SUBCLASSING AnyEvent::Handle |
1517 | |
1561 | |
1518 | In many cases, you might want to subclass AnyEvent::Handle. |
1562 | In many cases, you might want to subclass AnyEvent::Handle. |
1519 | |
1563 | |
1520 | To make this easier, a given version of AnyEvent::Handle uses these |
1564 | To make this easier, a given version of AnyEvent::Handle uses these |