DBordello has asked for the wisdom of the Perl Monks concerning the following question:

Is it possible to listen for 2 sockets within the same script? I would like to pass each connection off to a sub, the sub depending on which socket it connects.
To listen on one I was using:
while (my $active_sock = $sock->accept()) { fork and send it to a sub +}
I am unable (through thought and experimentation) figure out a way to do that on two sockets. I have tried IO::Select but I don't think that would work because I need to pass a connection to a specific sub, not just all connections to one sub.
Putting an || in the while statement and adding both listening functions does not work because the second never gets evaluated (it gets stuck waiting for the first one).
Any insight? db

Replies are listed 'Best First'.
Re: Listening on 2 Sockets
by pg (Canon) on Apr 03, 2003 at 04:36 UTC
    One solution is to use thread, have two socket listening on two threads.
    #!/usr/bin/perl use threads; use IO::Socket::INET; use strict; threads->create(\&listening, 3000); threads->create(\&listening, 3001); <STDIN>; sub listening { my $port = shift; my $listener = new IO::Socket::INET(Listen => 10, Timeout => 200, +LocalPort => $port); while (1) { my $client = $listener->accept(); print "port $port got connection\n"; #do something } }
•Re: Listening on 2 Sockets
by merlyn (Sage) on Apr 03, 2003 at 07:28 UTC
Re: Listening on 2 Sockets
by jasonk (Parson) on Apr 03, 2003 at 04:18 UTC
    #!/usr/bin/perl -w use strict; use IO::Select; use IO::Socket; my $sock1 = new IO::Socket::INET(Listen => 1, LocalPort => 1234); my $sock2 = new IO::Socket::INET(Listen => 1, LocalPort => 1235); my $select = new IO::Select; $select->add($sock1); $select->add($sock2); while(my @ready = $select->can_read) { foreach my $fh (@ready) { if($fh == $sock1) { &fork_and_handle_sock1(); } elsif($fh == $sock2) { &fork_and_handle_sock2(); } } } sub fork_and_handle_sock1 { print "sock1\n"; } sub fork_and_handle_sock2 { print "sock2\n"; }

    We're not surrounded, we're in a target-rich environment!