Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl TCP Server handling multiple Client connections

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.

like image 713
Matt Avatar asked Oct 12 '25 11:10

Matt


1 Answers

Either fork, thread or do I/O multiplexing with select. Take a look at Net::Server and AnyEvent::Socket, too. For an example of I/O multiplexing, take a look at How can I accept multiple TCP connections in Perl?.

like image 135
Mark Johnson Avatar answered Oct 15 '25 18:10

Mark Johnson