Jordan Doyle
Jordan Doyle

Reputation: 3026

Infinite feof loop

When using feof or fgets the script will keep running until the 1 minute max execution mark.

my $socket = new IO::Socket::INET(
    LocalPort => '5000',
    Proto     => 'tcp',
    Listen    => 5,
    ReuseAddr => 1,
);

my $connection = $socket->accept();

$connection->send("\0"); # makes PHP send the contents

my $data = <$connection>;
if($data != "1234") {
    $connection->send("not accepted");
} else {
    $connection->send("accepted");
}

$connection->close();

PHP will not send the content until the 60 seconds has passed. When using fread it will pass the data (but will only get the \0 back) almost instantly.

$socket = fsockopen('tcp://192.168.56.101', 5000); // virtualbox IP
fwrite($socket, '1234');

echo fread($socket, 128);

fclose($socket);

The above script will execute almost instantly but only get \0.

while(!feof($socket)) {
    echo fread($socket, 128);
}

Using the above script will not send any data until the 60 seconds is up on execution.

Question

How do I get PHP to send data and retrieve all data from the perl socket without the 60 second execution timeout?

Upvotes: 4

Views: 858

Answers (1)

ChicagoRedSox
ChicagoRedSox

Reputation: 638

PHP is actually sending the data right away; the problem is Perl isn't doing anything with it. If you do this:

my $data = <$connection>;
print $data; #add this line
if($data != "1234") { ....

and then kill the PHP script with Ctrl-C (Windows -- don't know what the command is if you're using Linux), the Perl script will immediately output "1234". It's hanging up on the angle bracket operator because that is a readline (i.e. it's looking for a newline and never finding one). Either of the following got your code to work for me:

//in the PHP file
fwrite($socket, "1234\r\n");

or

#in the Perl file (instead of my $data = <$connection>)
my $data;
$connection->recv($data, 1024);

Edit: see comments below before just implementing a change. As hobbs mentions, recv is probably not the best choice, although it happened to work since it's not looking for a newline and the input is short. Sending a newline in some capacity (variant of the first suggestion) is probably the better option.

Upvotes: 2

Related Questions