Yes, as
bikeNomad suggested, you can use the four-argument select() or
IO::Select.
This way avoids the so-called busy-waiting by letting the kernel does the scanning of array of file descriptors of interest.
Once your socket is ready to read or write, the kernel wakes up your program, which then handles it.
Here's a simple client to send HEAD to a httpd:
#!/usr/bin/perl -w
use IO::Socket;
$|++;
my $client = IO::Socket::INET->new(
PeerAddr => 'www.satunet.com',
PeerPort => 80,
Proto => 'tcp',)
or die "Can't connect: $!";
$rin = $rout = $win = $wout = '';
vec($rin, $client->fileno, 1) = 1;
vec($win, $client->fileno, 1) = 1;
while (1) {
if (select($rout = $rin, $wout = $win, undef, 5) > 0) {
if (vec($rout, $client->fileno, 1)) {
while (<$client>) { print "Client read: $_" }
$client->close;
} elsif (vec($wout, $client->fileno, 1)) {
print $client "HEAD / HTTP/1.0\r\n\r\n";
}
} else { exit }
}
Using
IO::Select is much more convenient since it does the bit-vector works behind the curtain,
as well as its nice OO interface.
POE is also good, but it requires you to have some basic knowledge about state machine, otherwise its
programming style may be confusing. I'd recommend using JPRIT's Event module
if you want to explore the full power of event-driven programming.
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
|
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.