1 | #!/opt/perl/bin/perl |
1 | #!/opt/perl/bin/perl |
2 | use IO::Socket::INET; |
2 | use IO::Socket::INET; |
3 | use AnyEvent::Util; |
3 | use AnyEvent::Socket; |
4 | use AnyEvent::Handle; |
4 | use AnyEvent::Handle; |
5 | |
5 | |
6 | my $cv = AnyEvent->condvar; |
6 | my $cv = AnyEvent->condvar; |
7 | |
7 | |
8 | # Warning: IO::Socket::INET is going to do a BLOCKING |
|
|
9 | # DNS lookup. Please see AnyEvent::Util::inet_aton how to |
|
|
10 | # do nonblocking lookups! |
|
|
11 | my $sock = IO::Socket::INET->new ( |
|
|
12 | PeerAddr => "www.google.com:80", |
|
|
13 | Blocking => 0, |
|
|
14 | ) or die "Couldn't make socket: $!\n"; |
|
|
15 | |
|
|
16 | my $hdl; |
8 | my $hdl; |
17 | |
9 | |
18 | # The $watchobj is just a guard that you have to keep |
10 | my $watchobj = AnyEvent::Socket::tcp_connect ("www.google.com", 80, sub { |
19 | # referenced until you are done with the connect. |
|
|
20 | my $watchobj = AnyEvent::Util::connect ($sock, sub { |
|
|
21 | my ($sock) = @_; |
11 | my ($sock) = @_; |
|
|
12 | |
|
|
13 | unless ($sock) { |
|
|
14 | warn "couldn't connect: $!"; |
|
|
15 | return; |
|
|
16 | } |
22 | |
17 | |
23 | $hdl = |
18 | $hdl = |
24 | AnyEvent::Handle->new ( |
19 | AnyEvent::Handle->new ( |
25 | fh => $sock, |
20 | fh => $sock, |
26 | on_eof => sub { print "received eof\n"; undef $hdl } |
21 | on_eof => sub { print "received eof\n"; undef $hdl } |
… | |
… | |
33 | print "Yay, got line: $line\n"; |
28 | print "Yay, got line: $line\n"; |
34 | $cv->broadcast; |
29 | $cv->broadcast; |
35 | }); |
30 | }); |
36 | |
31 | |
37 | }, sub { |
32 | }, sub { |
38 | warn "Got error on connect: $!\n"; |
33 | 10 # the timeout |
39 | $cv->broadcast; |
34 | }); |
40 | }, 10); |
|
|
41 | |
35 | |
42 | $cv->wait; |
36 | $cv->wait; |