ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/AnyEvent/lib/AnyEvent/Intro.pod
(Generate patch)

Comparing AnyEvent/lib/AnyEvent/Intro.pod (file contents):
Revision 1.23 by root, Mon Jun 29 20:59:08 2009 UTC vs.
Revision 1.24 by root, Fri Jul 24 23:43:59 2009 UTC

185 185
186AnyEvent does, by default, not do any argument checking. This can lead to 186AnyEvent does, by default, not do any argument checking. This can lead to
187strange and unexpected results especially if you are trying to learn your 187strange and unexpected results especially if you are trying to learn your
188ways with AnyEvent. 188ways with AnyEvent.
189 189
190AnyEvent supports a special "strict" mode, off by default, which does very 190AnyEvent supports a special "strict" mode - off by default - which does very
191strict argument checking, at the expense of being somewhat slower. During 191strict argument checking, at the expense of being somewhat slower. During
192development, however, this mode is very useful. 192development, however, this mode is very useful.
193 193
194You can enable this strict mode either by having an environment variable 194You can enable this strict mode either by having an environment variable
195C<PERL_ANYEVENT_STRICT> with a true value in your environment: 195C<PERL_ANYEVENT_STRICT> with a true value in your environment:
833So, here is how you would do it with C<AnyEvent::Handle>: 833So, here is how you would do it with C<AnyEvent::Handle>:
834 834
835 sub http_get { 835 sub http_get {
836 my ($host, $uri, $cb) = @_; 836 my ($host, $uri, $cb) = @_;
837 837
838 tcp_connect $host, "http", sub {
839 my ($fh) = @_
840 or $cb->("HTTP/1.0 500 $!");
841
842 # store results here 838 # store results here
843 my ($response, $header, $body); 839 my ($response, $header, $body);
844 840
845 my $handle; $handle = new AnyEvent::Handle 841 my $handle; $handle = new AnyEvent::Handle
846 fh => $fh, 842 connect => [$host => 'http'],
847 on_error => sub { 843 on_error => sub {
848 undef $handle;
849 $cb->("HTTP/1.0 500 $!"); 844 $cb->("HTTP/1.0 500 $!");
845 $handle->destroy; # explicitly destroy handle
850 }, 846 },
851 on_eof => sub { 847 on_eof => sub {
852 undef $handle; # keep it alive till eof
853 $cb->($response, $header, $body); 848 $cb->($response, $header, $body);
849 $handle->destroy; # explicitly destroy handle
854 }; 850 };
855 851
856 $handle->push_write ("GET $uri HTTP/1.0\015\012\015\012"); 852 $handle->push_write ("GET $uri HTTP/1.0\015\012\015\012");
857 853
858 # now fetch response status line 854 # now fetch response status line
859 $handle->push_read (line => sub { 855 $handle->push_read (line => sub {
860 my ($handle, $line) = @_; 856 my ($handle, $line) = @_;
861 $response = $line; 857 $response = $line;
862 }); 858 });
863 859
864 # then the headers 860 # then the headers
865 $handle->push_read (line => "\015\012\015\012", sub { 861 $handle->push_read (line => "\015\012\015\012", sub {
866 my ($handle, $line) = @_; 862 my ($handle, $line) = @_;
867 $header = $line; 863 $header = $line;
868 }); 864 });
869 865
870 # and finally handle any remaining data as body 866 # and finally handle any remaining data as body
871 $handle->on_read (sub { 867 $handle->on_read (sub {
872 $body .= $_[0]->rbuf; 868 $body .= $_[0]->rbuf;
873 $_[0]->rbuf = ""; 869 $_[0]->rbuf = "";
874 });
875 }; 870 });
876 } 871 }
877 872
878And now let's go through it step by step. First, as usual, the overall 873And now let's go through it step by step. First, as usual, the overall
879C<http_get> function structure: 874C<http_get> function structure:
880 875
881 sub http_get { 876 sub http_get {
882 my ($host, $uri, $cb) = @_; 877 my ($host, $uri, $cb) = @_;
883 878
884 tcp_connect $host, "http", sub { 879 # store results here
885 ... 880 my ($response, $header, $body);
886 }; 881
882 my $handle; $handle = new AnyEvent::Handle
883 ... create handle object
884
885 ... push data to write
886
887 ... push what to expect to read queue
887 } 888 }
888 889
889Unlike in the finger example, this time the caller has to pass a callback 890Unlike in the finger example, this time the caller has to pass a callback
890to C<http_get>. Also, instead of passing a URL as one would expect, the 891to C<http_get>. Also, instead of passing a URL as one would expect, the
891caller has to provide the hostname and URI - normally you would use the 892caller has to provide the hostname and URI - normally you would use the
892C<URI> module to parse a URL and separate it into those parts, but that is 893C<URI> module to parse a URL and separate it into those parts, but that is
893left to the inspired reader :) 894left to the inspired reader :)
894 895
895Since everything else is left to the caller, all C<http_get> does it to 896Since everything else is left to the caller, all C<http_get> does it to
896initiate the connection with C<tcp_connect> and leave everything else to 897initiate the connection by creating the AnyEvent::Handle object (which
897it's callback. 898calls C<tcp_connect> for us) and leave everything else to it's callback.
898 899
899The first thing the callback does is check for connection errors and 900The handle object is created, unsurprisingly, by calling the C<new>
900declare some variables: 901method of L<AnyEvent::Handle>:
901 902
902 my ($fh) = @_ 903 my $handle; $handle = new AnyEvent::Handle
904 connect => [$host => 'http'],
905 on_error => sub {
903 or $cb->("HTTP/1.0 500 $!"); 906 $cb->("HTTP/1.0 500 $!");
904 907 $handle->destroy; # explicitly destroy handle
908 },
909 on_eof => sub {
905 my ($response, $header, $body); 910 $cb->($response, $header, $body);
911 $handle->destroy; # explicitly destroy handle
912 };
913
914The C<connect> argument tells AnyEvent::Handle to call C<tcp_connect> for
915the specified host and service/port.
916
917The C<on_error> callback will be called on any unexpected error, such as a
918refused connection, or unexpected connection while reading the header.
906 919
907Instead of having an extra mechanism to signal errors, connection errors 920Instead of having an extra mechanism to signal errors, connection errors
908are signalled by crafting a special "response status line", like this: 921are signalled by crafting a special "response status line", like this:
909 922
910 HTTP/1.0 500 Connection refused 923 HTTP/1.0 500 Connection refused
911 924
912This means the caller cannot distinguish (easily) between 925This means the caller cannot distinguish (easily) between
913locally-generated errors and server errors, but it simplifies error 926locally-generated errors and server errors, but it simplifies error
914handling for the caller a lot. 927handling for the caller a lot.
915 928
916The next step finally involves L<AnyEvent::Handle>, namely it creates the 929The error callback also destroys the handle explicitly, because we are not
917handle object: 930interested in continuing after any errors. In AnyEvent::Handle callbacks
931you have to call C<destroy> explicitly to destroy a handle. Outside of
932those callbacks you cna just forget the object reference and it will be
933automatically cleaned up.
918 934
919 my $handle; $handle = new AnyEvent::Handle 935Last not least, we set an C<on_eof> callback that is called when the
920 fh => $fh, 936other side indicates it has stopped writing data, which we will use to
921 on_error => sub { 937gracefully shut down the handle and report the results. This callback is
922 undef $handle; 938only called when the read queue is empty - if the read queue expects some
923 $cb->("HTTP/1.0 500 $!"); 939data and the handle gets an EOF from the other side this will be an error
924 }, 940- after all, you did expect more to come.
925 on_eof => sub {
926 undef $handle; # keep it alive till eof
927 $cb->($response, $header, $body);
928 };
929 941
930The constructor expects a file handle, which gets passed via the C<fh> 942If you wanted to write a server using AnyEvent::Handle, you would use
943C<tcp_accept> and then create the AnyEvent::Handle with the C<fh>
931argument. 944argument.
932 945
933The remaining two argument pairs specify two callbacks to be called on
934any errors (C<on_error>) and in the case of a normal connection close
935(C<on_eof>).
936
937In the first case, we C<undef>ine the handle object and pass the error to
938the callback provided by the callback - done.
939
940In the second case we assume everything went fine and pass the results
941gobbled up so far to the caller-provided callback. This is not quite
942perfect, as when the server "cleanly" closes the connection in the middle
943of sending headers we might wrongly report this as an "OK" to the caller,
944but then, HTTP doesn't support a perfect mechanism that would detect such
945problems in all cases, so we don't bother either.
946
947=head3 The write queue 946=head3 The write queue
948 947
949The next line sends the actual request: 948The next line sends the actual request:
950 949
951 $handle->push_write ("GET $uri HTTP/1.0\015\012\015\012"); 950 $handle->push_write ("GET $uri HTTP/1.0\015\012\015\012");
952 951
953No headers will be sent (this is fine for simple requests), so the whole 952No headers will be sent (this is fine for simple requests), so the whole
954request is just a single line followed by an empty line to signal the end 953request is just a single line followed by an empty line to signal the end
955of the headers to the server. 954of the headers to the server.
956 955
962array. 961array.
963 962
964The deeper reason is that at some point in the future, there might 963The deeper reason is that at some point in the future, there might
965be C<unshift_write> as well, and in any case, we will shortly meet 964be C<unshift_write> as well, and in any case, we will shortly meet
966C<push_read> and C<unshift_read>, and it's usually easiest to remember if 965C<push_read> and C<unshift_read>, and it's usually easiest to remember if
967all those functions have some symmetry in their name. 966all those functions have some symmetry in their name. So C<push> is used
967as the opposite of C<unshift> in AnyEvent::Handle, not as the opposite of
968C<pull> - just like in Perl.
969
970Note that we call C<push_write> right after creating the AnyEvent::Handle
971object, before it has had time to actually connect to the server. This is
972fine, pushing the read and write requests will simply queue them in the
973handle object until the connection has been established. Alternatively, we
974could do this "on demand" in the C<on_connect> callback.
968 975
969If C<push_write> is called with more than one argument, then you can even 976If C<push_write> is called with more than one argument, then you can even
970do I<formatted> I/O, which simply means your data will be transformed in 977do I<formatted> I/O, which simply means your data will be transformed in
971some ways. For example, this would JSON-encode your data before pushing it 978some ways. For example, this would JSON-encode your data before pushing it
972to the write queue: 979to the write queue:
985status, a single paragraph of headers ended by an empty line, and the 992status, a single paragraph of headers ended by an empty line, and the
986request body, which is simply the remaining data on that connection. 993request body, which is simply the remaining data on that connection.
987 994
988For the first two, we push two read requests onto the read queue: 995For the first two, we push two read requests onto the read queue:
989 996
990 # now fetch response status line 997 # now fetch response status line
991 $handle->push_read (line => sub { 998 $handle->push_read (line => sub {
992 my ($handle, $line) = @_; 999 my ($handle, $line) = @_;
993 $response = $line; 1000 $response = $line;
994 }); 1001 });
995 1002
996 # then the headers 1003 # then the headers
997 $handle->push_read (line => "\015\012\015\012", sub { 1004 $handle->push_read (line => "\015\012\015\012", sub {
998 my ($handle, $line) = @_; 1005 my ($handle, $line) = @_;
999 $header = $line; 1006 $header = $line;
1000 }); 1007 });
1001 1008
1002While one can simply push a single callback to parse the data the 1009While one can simply push a single callback to parse the data the
1003queue, I<formatted> I/O really comes to our advantage here, as there 1010queue, I<formatted> I/O really comes to our advantage here, as there
1004is a ready-made "read line" read type. The first read expects a single 1011is a ready-made "read line" read type. The first read expects a single
1005line, ended by C<\015\012> (the standard end-of-line marker in internet 1012line, ended by C<\015\012> (the standard end-of-line marker in internet
1016many requests as we want, and AnyEvent::Handle will handle them in order. 1023many requests as we want, and AnyEvent::Handle will handle them in order.
1017 1024
1018There is, however, no read type for "the remaining data". For that, we 1025There is, however, no read type for "the remaining data". For that, we
1019install our own C<on_read> callback: 1026install our own C<on_read> callback:
1020 1027
1021 # and finally handle any remaining data as body 1028 # and finally handle any remaining data as body
1022 $handle->on_read (sub { 1029 $handle->on_read (sub {
1023 $body .= $_[0]->rbuf; 1030 $body .= $_[0]->rbuf;
1024 $_[0]->rbuf = ""; 1031 $_[0]->rbuf = "";
1025 }); 1032 });
1026 1033
1027This callback is invoked every time data arrives and the read queue is 1034This callback is invoked every time data arrives and the read queue is
1028empty - which in this example will only be the case when both response and 1035empty - which in this example will only be the case when both response and
1029header have been read. The C<on_read> callback could actually have been 1036header have been read. The C<on_read> callback could actually have been
1030specified when constructing the object, but doing it this way preserves 1037specified when constructing the object, but doing it this way preserves
1089B<S>ecurity is the official name for what most people refer to as C<SSL>) 1096B<S>ecurity is the official name for what most people refer to as C<SSL>)
1090that contains standard HTTP protocol exchanges. The only other difference 1097that contains standard HTTP protocol exchanges. The only other difference
1091to HTTP is that by default it uses port C<443> instead of port C<80>. 1098to HTTP is that by default it uses port C<443> instead of port C<80>.
1092 1099
1093To implement these two differences we need two tiny changes, first, in the 1100To implement these two differences we need two tiny changes, first, in the
1094C<tcp_connect> call we replace C<http> by C<https>): 1101C<connect> parameter, we replace C<http> by C<https> to connect to the
1102https port:
1095 1103
1096 tcp_connect $host, "https", sub { ... 1104 connect => [$host => 'https'],
1097 1105
1098The other change deals with TLS, which is something L<AnyEvent::Handle> 1106The other change deals with TLS, which is something L<AnyEvent::Handle>
1099does for us, as long as I<you> made sure that the L<Net::SSLeay> module 1107does for us, as long as I<you> made sure that the L<Net::SSLeay> module
1100is around. To enable TLS with L<AnyEvent::Handle>, we simply pass an 1108is around. To enable TLS with L<AnyEvent::Handle>, we simply pass an
1101additional C<tls> parameter to the call to C<AnyEvent::Handle::new>: 1109additional C<tls> parameter to the call to C<AnyEvent::Handle::new>:

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines