Here's some building blocks for you. It's just an extension of the example at the end of the IO::Select perldoc page with some features from your stated problem added.

#!/usr/bin/perl # http://perlmonks.org/?node_id=1120916 use IO::Socket; use IO::Select; use strict; my ($port, $current, $cycle) = (shift // 6667); my $listen = IO::Socket::INET->new(LocalPort => $port, Listen => 9, Re +use => 1) or die "$@ opening socket on port $port"; my $sel = IO::Select->new($listen, 0); while(1) { for my $h ($sel->can_read) { if($h == $listen) { $sel->add(my $new = $h->accept); $current //= $new; print "accepted from: ", $new->peerhost, ":", $new->peerport, "\ +n"; } elsif($h == 0) { sysread STDIN, my $in, 1024; # ignore $current = (grep $_ > 0 && $_ != $listen, $sel->handles) [++$cycle % ($sel->count - 2 || 1)]; print $current ? "switch to " . $current->peerhost . ':' . $current->peerpor +t . "\n" : "no clients\n"; } elsif(sysread $h, my $in, 1024) { $h == $current and print $in; } else { $sel->remove($h); $h == $current and undef $current, print "client exited\n"; } } }

As others (including me) have said, this kind of problem should be done in one of the async frameworks, but sometimes a plain example can make for a decent tutorial.

Or not.


In reply to Re^3: How to serve multiple socket clients Perl by Anonymous Monk
in thread How to serve multiple socket clients Perl by perlnwb

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.