On Apr 11, 2008, at 9:23 PM, Eric Wilhelm wrote:
...
I would like the "publish" clients to connect to a server, then
publish
their message and disconnect. (Optionally, they can stay connected
and
publish more messages.)
The "subscribe" clients would hold persistent connections to the
server
(there are only 2 subscribers, though there could be more) and receive
the messages immediately after publication.
...
http://scratchcomputing.com/svn/misc/pubsubserver
To put that in some rough but short code:
my $fh;
while(my $client = $socket->accept()) {
my $pid = open($fh, '|-') and next;
if(pub) {
while(<$client>) { print $fh $_ }
}
else {
while(<>) { relay_to_subscriber($client) }
}
exit;
}
...
I implemented something vaguely like this in a single threaded manner
a couple of years back. My implementation looked something like this:
while (1) {
my $msg;
my $client = $socket->accept;
if (!$client) { # time out, send a keepalive to listeners
$msg = $self->make_keepalive_msg();
} else {
my $response = $self->handle($c);
if ($response->is_new_listener) {
$self->add_listener($client);
$socket->timeout($LISTENER_TIMEOUT);
} elsif ($response->should_send_to_listeners) {
$msg = $response->make_msg();
}
}
if ($msg) {
for my $client ($self->get_listeners) {
if (!$client->connected) {
$self->remove_listener($client);
$socket->timeout(undef) if ! @listeners;
} else {
print {$client} $msg;
}
}
}
}
My real implementation did a lot more error handling, of course, and
spoke SOAP but still netted under 200 lines. Perhaps a difference
between your problem and mine is that my messages were always short
and my accepting server was allowed to be single threaded (very low
traffic), so looping over the listeners in the main accept loop was
fine.
Mine had to work on Windows, so I did as little forking as possible.
Chris