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

I am trying to open a series of sockets (10) to receive some data. As soon as a new one is opened the previous one is closed with FIN / Fin ACK etc. Please tell me if this approach should work or what is wrong with it. Do I HAVE to Fork or thread etc.? This is my 1st. perl prog.

This is the code.

#!/usr/bin/perl -w $IP_Addr = "ss6"; #$TCP_port = (1025); print "Enter start TSG port: "; chomp ($TCP_port = <stdin>); print "Enter last TSG port: "; chomp ($last_TSG = <stdin>); use IO::Socket; while ($TCP_port <= $last_TSG) { open_TSG ($IP_Addr, $TCP_port); $TCP_port +=1 ; } sub open_TSG { # use IO::Socket; $remote = IO::Socket::INET->new( Proto => "tcp", PeerAddr => $IP_Addr, PeerPort => $TCP_port, ) or die "Cannot conect to port $TCP_port at $IP_Addr"; $response = <$remote>; print "$TCP_port active\n"; print $remote "g\n"; } while ( <$remote> ) {print </dev/null> }

Replies are listed 'Best First'.
Re: IO socket closed when new one is opened.
by Fletch (Bishop) on Jan 06, 2005 at 17:50 UTC

    Erm, are you:

    • complaining that they're closing when you open a new socket (because you're using the same (global) $remote to hold the reference to the socket object; as soon as you make the next object you lose the reference to the old one and it gets destroyed and hence close() will be called on it)
    • or asking if that's what will happen when you make a new IO::Socket instance?
Re: IO socket closed when new one is opened.
by revdiablo (Prior) on Jan 06, 2005 at 18:30 UTC
    Do I HAVE to Fork or thread etc.?

    No, you can use a select loop. If you're not already familiar with the unix select system call, Perl's builtin might be a little intimidating.

    In that case, check out IO::Select. It puts a friendly object-oriented wrapper around the standard call. Also, note that there's an example of a socket server in IO::Select's docs. This should be all you need to get started.

Re: IO socket closed when new one is opened.
by BUU (Prior) on Jan 06, 2005 at 23:43 UTC
    The reason the sockets close is becuase thats what IO::Socket's do when they get destroyed. And when you overwrite the previous IO::Socket stored in $remote, it gets destroyed and disconnects it self. If you don't wish this to happen, you need to keep track fo each socket individually.