now I have also the outgoing net, which was simpler but not very simple
[breadcrumbs.git] / src / lib / Bcd / Clients / ClientsListeners.pm
blob5f52af731a6c52f526e3389309b99605acdeaf02
1 package Bcd::Clients::ClientsListeners;
3 # This file is part of the breadcrumbs daemon (bcd).
4 # Copyright (C) 2007 Pasqualino Ferrentino
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 # General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
19 # 02110-1301, USA.
21 # Contact: lino.ferrentino@yahoo.it (in Italian, English or German).
23 #this file contains the set of the listeners in our program.
24 #each listener is in its own thread.
26 #this file is a singleton.
28 use strict;
29 use warnings;
30 use Class::Singleton;
32 use Bcd::Clients::Listener;
34 use vars qw(@ISA);
35 @ISA = qw(Class::Singleton);
36 use constant EOL => "\015\012";
38 use constant{
39 # Some constants to initialize the number of threads in this program...
40 INITAL_LISTENERS => 10,
41 MAX_LISTENERS => 20,
44 sub _new_instance{
45 my ($class, $script) = @_;
47 my $self = {};
49 bless ($self, $class);
51 $self->_create_the_listeners($script);
53 #this is the hash which has the clients which must be closed...
54 $self->{"clients"} = {};
56 return $self;
59 sub _create_the_listeners{
61 my ($self, $script) = @_;
63 #if you want the script you have only one listener...
64 my @listeners;
66 my $listeners_num;
68 if ($script == 1) {
69 $listeners_num = 1;
70 } else {
71 $listeners_num = INITAL_LISTENERS;
74 for ( my $i = 0 ; $i < $listeners_num ; ++$i){
75 #ok, let's create them
77 my $listener = Bcd::Clients::Listener->new($script);
78 push (@listeners, $listener);
81 $self->{"listeners"} = \@listeners;
84 #this function is called whenever a new client wants to talk to the
85 #daemon. this function can blocks the incoming client because we have
86 #not reasource available to serve it
87 sub a_new_client_has_arrived{
89 my ($self, $client) = @_;
91 #ok, let's try to get a free listener for this client
92 my $served = 0;
94 while (!$served){
95 for (my $i = 0 ; $i < INITAL_LISTENERS ; ++$i){
96 if ($self->{"listeners"}[$i]->try_to_serve_this_client($client) == 0){
97 #ok... I am able to go on
98 $served = 1;
99 last;
103 if (!$served){
104 print $client "BCD busy, please wait..." . EOL;
105 sleep(2);