I have ran into an issue while creating a hash of socket id's and trying to share them across multiple threads. I get the error "Invalid value for shared scalar" due to the fact that the usage I have is trying to share an object reference (the socket id ref). This of course is not allowed but I can not think of an alternative to make this work.
#!/usr/bin/perl -w
use strict;
use threads;
use threads::shared;
use IO::Socket::INET;
my $sock = new IO::Socket::INET (
LocalHost => 'localhost',
LocalPort => '12345',
Proto => 'tcp',
Listen => 10,
Blocking => 1,
);
die "Could not create socket: $!\n" unless $sock;
my($thread, $cnt);
my %usersocks : shared;
while (my $UserSock = $sock->accept()) {
$cnt++;
$thread = threads->create(\&connection, $UserSock, $cnt);
}
$_->join for threads->list;
sub connection {
my ($sockID, $cnt) = @_;
my $sockData;
lock(%usersocks);
$usersocks{$cnt} = $sockID;
while($sockID->recv($sockData, 1024)) {
print $sockData;
#debug code to see contents of hash
while(my($key, $value) = each(%usersocks)) {
print "$key => $value\n";
}
$usersocks{$_}->send($sockData) for sort(keys %usersocks);
}
close($sockID);
delete $usersocks{$sockID};
}
The line $usersocks{$cnt} = $sockID; is of course my issue because $sockID is the obj reference to the connection id. Is there a way of accomplishing this? I ultimately want all data sent to this server application to be sent out to all threaded clients.
-
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.
|