I did end up using threads actually.
In the case that I can't open a non-blocking listener, I make a thread and share the messages in an array. It worked great and I can get the IP from the recv().
Really, the best part is, this is the first time I've every needed to use a thread and now that I know how, it's like there's a whole new world out there.
And for posterity, here is my original non-blocking loop along with my new magical threaded version.
sub listen {
my $this = shift;
if( $this->{blocking} ) {
if( not $this->{blocking_thread} ) {
$this->{blocking_thread} = new threads( \&_blocking_listen
+, $this );
}
my @msgs = map([ split /^G^G/, $_ ], @global_shared_messages);
@global_shared_messages = ();
return @msgs;
}
my @msgs = ();
my $msg = "";
while( my $portaddr = recv($this->{in}, $msg, 1024*1024, 0) ) {
my ($portno, $ipaddr) = sockaddr_in($portaddr);
my $ip = inet_ntoa($ipaddr);
push @msgs, [$ip, $this->_transform($msg)];
}
return @msgs;
}
sub _blocking_listen {
my $this = shift; {
my $msg = "";
while( my $portaddr = recv($this->{in}, $msg, 1024*1024, 0) )
+{
my ($portno, $ipaddr) = sockaddr_in($portaddr);
my $ip = inet_ntoa($ipaddr);
push @global_shared_messages, "$ip^G^G" . $this->_transfor
+m($msg);
}
redo; # we stay in here forever, btw.
}
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.