in reply to AnyEvent server/client don't cooperate

You need to keep the handle '$hdl' in scope. For the client, you can just move the declaration to global scope. For the server, you need to put them into some sort of global hash so that there can be multiple of them, and when the connection closes, you can remove the one that closed. Of course, in an object-oriented program you would have the server object maintain the connection set in an attribute, so that when the server goes out of scope it closes all its connections.

A less recommended quick-and-dirty way to keep them alive is to have it make a reference to itself, like $hdl->{self}= $hdl; and then you can have the on_error and on_eof remove that reference and allow it to get freed.