I have the following Perl problem: I am trying to build a simple network-enabled forwarder/consumer script.
the forwarder part loops and calls a local blocking function to retrieve a new string (i.e., from an existing library)
the consumer part consists of a server where multiple clients can connect to the server (TCP socket)
the idea is that every message retrieved by the forwarder part is passed on to the clients, i.e., forwarded to all connected client sockets.
I looked into threads/shared variables, but sockets cannot be shared this way. I also looked into the POE TCP Forwarding example (http://poe.perl.org/?POE_Cookbook/TCP_Forwarding), but there, I did not find out how to start a thread that can still use send to the %clients or the poe_kernel in this specific example (maybe there is a way ...).
In a nutshell:
- I need to fork or use some other threading mechanism to first start the forwarder and initiate the loop on the retrieval function
- I need to hand the retrieved data over to all connected clients/consumers.
Here is what I intend to do (BEWARE: abstract code):
$pid = fork();
if ($pid == 0)
{
# forwarder/producer thread
while(1)
{
$string = blocking_receive_function();
foreach(@clients)
{
print($_ "$string");
}
}
}
else
{
# start server and add clients to consumer list
$server = IO::Socket::INET->new( ... );
while ($client = $server->accept()) {
push(@clients, $client);
# fork for this client (to allow others) and
# wait for specific client it closes connection
}
}
Any suggestions/recommendations for a good and efficient way to implement such a application is highly appreciated!
Ok, there is more than one way to do it. But IMHO the simplest is to use Coro.
Here is quick example