i use a Perl script to create a TCP server. It works fine, but i need to modify it so it accepts multiple connections. This is the code i use:
use IO::Socket::INET;
# auto-flush on socket
$| = 1;
# creating a listening socket
my $socket = new IO::Socket::INET (
LocalHost => '0.0.0.0',
LocalPort => '5000',
Proto => 'tcp',
Listen => 5,
Reuse => 1
);
die "cannot create socket $!\n" unless $socket;
print "server waiting for client connection on port 5000\n";
while(1)
{
# waiting for a new client connection
my $client_socket = $socket->accept();
# get information about a newly connected client
my $client_address = $client_socket->peerhost();
my $client_port = $client_socket->peerport();
print "connection from $client_address:$client_port\n";
# read up to 1024 characters from the connected client
my $data = ":123456F#";
$client_socket->send($data);
# write response data to the connected client
$data = "";
$client_socket->recv($data, 1024);
print "received data: $data\n";
# notify client that response has been sent
shutdown($client_socket, 1);
}
$socket->close();
I need to modify the above code in order to work for multiple connections. I'd really appreciate any help. Thanks
There are two key ways of handling multiple sockets.
The first is - making use of
IO::Select- which has acan_readfunction - this allows you to test whether a socket has data to read, and you can just iterate your socket list. Read the doc onIO::Select, as it has an example of how to do exactly what you're wanting.The other approach is parallel processing. Specifically using either threading or forking to handle the
$client_socketasynchronously. I'll refer you to: Perl daemonize with child daemons (mostly because rewriting parallel code is a bit more convoluted, and so perhaps out of scope). I'd suggest you probably want a 'forking' approach, as that's generally better suited to the style of parallelism.