in reply to Re^4: share socket connections amongst multiple threads?
in thread share socket connections amongst multiple threads?
When the server accept()'s a connection I add the connection id to a hash ...
What do you mean by "connection id"?
My assumption is that you mean an IO::Socket::INET handle. This is a blessed ref:
use IO::Socket::Inet;; $sock = IO::Socket::INET->new( PeerAddr => 'www.perl.org', PeerPort => 'http(80)', Proto => 't +cp' );; print $sock;; IO::Socket::INET=GLOB(0x1a05ec0)
which, for very good reason, you cannot put into a shared hash.
Basically, the methods that are attached to a blessed object like IO::Socket::INET=GLOB(0x1a05ec0) are tied to the thread in which the object handle (a GLOB in this case) is instantiated. So, if you share that object with another thread and that other thread attempts to call a method upon it, it will try to invoke code from the other thread. That cannot work, which is why Perl stops you from trying to do that.
There are two approached to solving this problem that I am aware of:
This is easier to arrange by having a "controller" thread that also has a queue and each client forwards a copy of data it receives to the contoller via it's queue and it forwards it to each of the other clients.
Again, this works best if a central controller thread is given access to handles from each of the client handles and it reblesses them. The clients would then forward their messages to the controller and it would forward them (directly) to the clients via the reblessed handles. This still leaves the problem of conveying those handles from the clients to the controller. Not insurmountable, but requires some jiggery pokery.
All in all, the queues method is probably easier.
|
---|