Perl TCP Server handling multiple Client connections
Posted
by
Matt
on Stack Overflow
See other posts from Stack Overflow
or by Matt
Published on 2011-01-31T22:42:59Z
Indexed on
2011/01/31
23:25 UTC
Read the original article
Hit count: 191
I'll preface this by saying I have minimal experience with both Perl and Socket programming, so I appreciate any help I can get. I have a TCP Server which needs to handle multiple Client connections simultaneously and be able to receive data from any one of the Clients at any time and also be able to send data back to the Clients based on information it's received. For example, Client1 and Client2 connect to my Server. Client2 sends "Ready", the server interprets that and sends "Go" to Client1. The following is what I have written so far:
my $sock = new IO::Socket::INET
{
LocalHost => $host, // defined earlier in code
LocalPort => $port, // defined earlier in code
Proto => 'tcp',
Listen => SOMAXCONN,
Reuse => 1,
};
die "Could not create socket $!\n" unless $sock;
while ( my ($new_sock,$c_addr) = $sock->accept() )
{
my ($client_port, $c_ip) = sockaddr_in($c_addr);
my $client_ipnum = inet_ntoa($c_ip);
my $client_host = "";
my @threads;
print "got a connection from $client_host", "[$client_ipnum]\n";
my $command;
my $data;
while ($data = <$new_sock>)
{
push @threads, async \&Execute, $data;
}
}
sub Execute
{
my ($command) = @_;
// if($command) = "test" {
// send "go" to socket1
print "Executing command: $command\n";
system($command);
}
I know both of my while loops will be blocking and I need a way to implement my accept command as a thread, but I'm not sure the proper way of writing it.
© Stack Overflow or respective owner