in reply to Two TCP Connections, one script
Presumably you want the data from both of these connections to be in the same memory space so you can combine the data in some way. This requirement would preclude the use of fork since data read by one process is not accessible by another process. On the other hand, if you don't need to combine the data from these two connections, then a fork solution is possible and could be simpler than an IO::Select solution. If you tell us more about what your program is going to do with the data is receives from the two connections, we can advise you on whether or not a fork solution is possible.
Here's a fragment of code which illustrates the use of IO::Select. It assumes that the data read from the input handles $h1 and $h2 is line oriented data, and when a complete line is received the appropriate handler is called:
use IO::Select; my $s = new IO::Select; $s->add($h1); $s->add($h2); my (%handler, %buf); $handler{$h1} = sub { ...handle a line from $h1... }; $handler{$h2} = sub { ...handle a line from $h2... }; while ($s->count) { my @ready = $s->can_read(); for my $h (@ready) { my $nr = sysread($h, $buf{$h}, 1024, length($buf{$h})); if ($nr == 0) { # eof detected $s->remove($h); } else { if ($buf{$h} =~ s/\A(.*?)\n//) { $handler{$h}->($1); } } } }
The above fragment of code is generically useful in the following sense: we can accomplish most of what you want to do using the netcat command with the above handling code:
open(my $h1, "nc server.com 12345|"); open(my $h2, "nc server.com 6789|"); # now call the above I/O handler loop
In fact, we can also get graceful reconnects with a simple shell script:
This approach may have to be tweaked if you need to send data to the server, but it illustrates a potential way of decomposing the problem.open(my $h1, "while true; do nc server.com 12345; sleep 10; done|"); # ditto for $h2
|
|---|