OK, so I want to build myself a program that does things while listening for messages on a socket. NB, both are important. It has to listen, and it has to do stuff.

So I looked into IO::Select and non-blocking IO, and wrote (something like) this:

while (1) { print "yo\n"; while ( my @handles = $self->{daemon}->can_read(1) ) { foreach ( @handles ) { if ($_ == $self->{listener}) { my $new_sock = $self->{listener}->accept or die "accept: $!"; $self->{daemon}->add( $new_sock); } else { my @rawmsg = $_->getlines; print @rawmsg; #$_->close; } } } }

Where,as you may guess $self->{daemon} is an IO::Select and $self->{listener} is a listening IO::Socket object. So I am trying to listen for calls, while periodically printing "yo". One day, "yo" will be replaced by interesting stuff.

My problem is this: if I don't do close on new sockets, the socket blocks, and I get:

yo yo yo yo message from client

and then nothing. But if I include the close() call, then the socket stops blocking, but can_read doesn't wait at all next time. I get:

yo yo yo yo message from client yo yo yo

with an infinite row of yos, and no more client messages.

How do I get can_read to be good second time round? More generally, is this a good way to go about things? I thought about forking a message receiver which would then pass messages via a pipe... but then I thought that I'd need to block while waiting for the pipe... seems like I need a language with better multithreading but maybe someone can tell me better...

best

dave hj~


In reply to non-blocking select with IO::Select by dash2

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.