Hi Guys,
I am trying to write a simple socket server which will accept multiple connections. I have this code code below which opens a socket and allows multiple connections. At the moment it only posts back to all the connected clients what someone has sent. But I am going to add switch statements here to perform various tasks depending on what the client sends.
This all works great but the problem I have is creating some sort of a child process running on the side which is an infinite loop. The infinite loops role is to send out a keep alive signal on the socket to all the clients every X seconds.
How do I do this? I am new to perl but I understand that I someone need to share $read_set to the child process? I tried IPC::Shareable but that failed so I am guessing I need to do something with pipe maybe? Can you please advice how I best accomplish this.
Thanks!
#!/usr/bin/perl -w
#
# Socket for communication
# Libraries
use IO::Socket;
use IO::Select;
use IO::Handle;
my @sockets;
my $s = new IO::Socket::INET (
LocalHost => '192.168.0.1',
LocalPort => '1234',
Proto => 'tcp',
Listen => 16,
Reuse => 1,
);
die "Could not create socket: $!\n" unless $s;
$read_set = new IO::Select(); # create handle set for reading
$read_set->add($s); # add the main socket to the set
while (1) {
my ($rh_set) = IO::Select->select($read_set, undef, undef, 0);
foreach $rh (@$rh_set) {
if ($rh == $s) {
# Client has connected
$ns = $rh->accept();
$read_set->add($ns);
} else {
$buf = <$rh>;
if($buf) {
# Client has sent something
$buf =~ s/\n|\r//g;
my @sockets = $read_set->can_write();
foreach my $sck(@sockets){print $sck "Hi every
+body, I just received the following for one of you: $buf\r\n";}
}
else {
# Client has disconnected
$read_set->remove($rh);
close($rh);
}
}
}
}
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.