Dear monks,

I'm trying to make a Perl script talk in a bi-directional manner with a C++ application using a socket. For this, I want to implement non-blocking socket read. Now, there is the nice IO::select which has the can_read() function. However, can_read() doesn't actually return how much I can read, only that I can. So, I've been reading the Cookbook and the Advanced Perl book, and my options are: (1) use multi-threading and (2) using fcntl() to make sysread() on the socket non-blocking. As you probably know, the nonblocking fcntl() (option 2) doesn't work on Windows, which apparently doesn't support this mode of work with files. I know I can go to option (1), but I would prefer not to - because my script is really quite simple. So, I came up with the following approach (pseudocode):

sub try_read(socket) buf = "" loop if (IO::Select->can_read socket) buf .= sysread(socket, 1); else exit loop return buf
This works, because if can_read says that there's data to read, there's at least one byte there, so I sysread with length 1 and concatenate the byte. When the data ends, the loop ends. Quite, simple.

Problem is, it looks inefficient. If I receive a packet of several KB, this loop will happily run thousands of times, each time calling can_read() and sysread(). However, I don't see any other option for robust non-blocking read on Windows, without using threads.

Any ideas / suggestions / enlightments ?

Thanks in advance


In reply to Non-blocking socket read on Windows by spurperl

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.