#!/usr/bin/perl use v5.10; use strict; use warnings; use AnyEvent::Socket; use AnyEvent::Handle; my $client = shift; # undef - server, or client my $path = "/tmp/socket"; my %data = (a => b => c => d =>); my $cv = AnyEvent->condvar; # Will send when client breaks connection if ($client) { # Client tcp_connect( "unix/", $path, sub { if (!@_) { # Error print STDERR "Failed connect to $path:$!\n"; $cv->end; return; } print "Client connected to $path\n"; my ($fh) = shift; #Create a handle and save it my $hdl; $hdl = AnyEvent::Handle->new( fh => $fh, on_error => sub { my ($hdl, $fatal, $msg) = @_; AE::log error => $msg; $hdl->destroy; $cv->send; }, on_eof => sub { my ($hdl1, $fatal, $msg) = @_; $hdl1->destroy; # destroy handle AE::log info => "Done."; $cv->send; } ); # Write to the server $hdl->push_write (storable => \%data); 1; }, ) } else { # Server print "Server\n"; tcp_server( "unix/", $path, sub { # Accept callback and start rolling my ($fh, $host, $port) = @_; print "ACCEPTED:host=$host\n"; my $hdl = AnyEvent::Handle->new( fh => $fh, on_error => sub { my ($hdl1, $fatal, $msg) = @_; AE::log error => $msg; $hdl1->destroy; $cv->send; }, on_eof => sub { my ($hdl1) = @_; $hdl1->destroy; # destroy handle AE::log info => "Done."; } ); # Read from the client $hdl->push_read (storable => sub { my ($hdl1, $data) = @_; print "Read @{[ref($data)]}\n"; }); 1; }, ); print "Listening on $path\n"; } $cv->recv;