initial commit
[map.git] / server.pl
1 #!/usr/bin/perl
2 use warnings;
3 use strict;
4 use IO::Socket;
5 use threads;
6 use threads::shared;
7 $|++;
8 print "$$ Server started\n";;  # do a "top -p -H $$" to monitor server
9
10 our @clients : shared;
11 @clients = ();
12
13 my $server = new IO::Socket::INET(
14     Timeout   => 7200,
15     Proto     => "tcp",
16     LocalPort => 10000,
17     Reuse     => 1,
18     Listen    => 3
19 );
20 my $num_of_client = -1;
21
22 while (1) {
23     my $client;
24
25     do {
26         $client = $server->accept;
27     } until ( defined($client) );
28
29     my $peerhost = $client->peerhost();
30     print "accepted a client $client, $peerhost, id = ", ++$num_of_client, "\n";
31     my $fileno = fileno $client;
32     push (@clients, $fileno);
33     #spawn  a thread here for each client
34     my $thr = threads->new( \&processit, $client, $fileno, $peerhost )->detach();
35 }
36 # end of main thread
37
38 sub processit {
39      my ($lclient,$lfileno,$lpeer) = @_; #local client
40         
41      if($lclient->connected){
42           # Here you can do your stuff
43           # I use have the server talk to the client
44           # via print $client and while(<$lclient>)
45           #print $lclient "$lpeer->Welcome to server\n";  
46           
47           while(<$lclient>){
48              # print $lclient "$lpeer->$_\n";
49               print "clients-> @clients\n";           
50               
51               foreach my $fn (@clients) { 
52                   open my $fh, ">&=$fn" or warn $! and die;
53                   print $fh  "$_"; 
54                   print "Sending $_\n";
55                   }
56            
57            }
58         
59     }
60   
61   #close filehandle before detached thread dies out
62   close( $lclient);
63   #remove multi-echo-clients from echo list
64   @clients = grep {$_ !~ $lfileno} @clients;
65
66 }
67 __END__