develooper Front page | perl.beginners | Postings from August 2010

chat server example

From:
Kammen van, Marco, Springer SBM NL
Date:
August 11, 2010 00:39
Subject:
chat server example
Message ID:
E0102EFB6FBB574BBF3EA287E822ADCB0BC703@SENLDOGO0144.springer-sbm.com
Hi All,

 

In this commonly used example I don't get something...

 

Why does it always echo the local ip address, even when people connected
from other systems are talking?

 

So if ip [1.2.3.4] talks it still echo's [5.6.7.8] instaid of [1.2.3.4]
I don't get that?

In this example you can never see who's talking cause it always uses the
IP of the system that you are on... 

 

 

#!/usr/bin/perl

 

use IO::Socket;

use IO::Select;

 

$max_clients = 10;

$port = 56789;

 

$new_client = IO::Socket::INET->new(Proto=>"tcp", LocalPort=>$port,
Listen=>$max_clients, Reuse=>1);

 

# create a new selection and add our basic socket for incoming
connections

$sel = IO::Select->new($new_client);

 

while (@ready = $sel->can_read) {

  # for every readable socket

  foreach $client (@ready) {

    # check if it is the basic socket

    if ($client == $new_client) {

      # if it is establish new connection

      $add = $client->accept;

      # print status to new user

      $count = $sel->count;

      print $add "--- $count users(s) online ---\n";

     # add new socket to the selection

     $sel->add($add);

     # if it is a already established connection

    } else {

      # get the message

      $message = <$client>;

      # remove last newline characters

      chop($message);

      chop($message);

      if ($message =~ /^\./) {

        if ($message eq ".quit") {

        # remove him from selection

         $sel->remove($client);

         # close his socket

         close $client;

        } elsif ($message eq ".version") {

          print $client "*** version 1.0 Beta ***\n";

        } else {

          print $client "*** commands are: .version .quit ***)\n";

        }

      } else {

        # send the message to all users

        foreach ($sel->can_write) {

          print $_ "[".$_->peerhost."] ".$message."\n"

        }

      }

    }

  }

}

 

- 

Marco van Kammen
Springer Science+Business Media
System Manager & Postmaster 

- 

van Godewijckstraat 30 | 3311 GX
Office Number: 05E21 
Dordrecht | The Netherlands 

-  

tel 

 +31(78)6576446

fax 

 +31(78)6576302

- 

www.springeronline.com <http://www.springeronline.com>  
www.springer.com <http://www.springer.com/> 

- 

 

 





nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About