kelly123
kelly123

Reputation: 29

How can I set Time out in socket_read

I would like to ask some help how can I time out in my socket_read if it takes reading in 60 seconds or reaches the limit that I set. I am having problem on how to implement this. I know it is dulplicate but I did not get help with first thread,that is why I ask some help.

Thank you in advance.

   <?php
    $time_limit = 60;

    set_time_limit (65);

    if(isset($_GET['comm'])){

        $command = $_GET['comm'];

        $host    = "xxx.xx.xxx.xx";
        $port    = xxxx;

        $start_time = time();
        $message =  $command;
        $socket = socket_create(AF_INET, SOCK_STREAM,0) or die("Could not create socket\n");



        $result = socket_connect($socket, $host, $port) or die("Couldn't connect to server: [$errorcode] $errormsg");
       $errorcode = socket_last_error();
     $errormsg = socket_strerror($errorcode);



 socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 60, "usec" => 0));

          socket_write($socket, $message, strlen($message)) or die("Could not send data to server\n");



  // This line I want to put time out if it reaches 60 seconds and 
// prompt it to user or show some echo "request time out".

    $resultserv = socket_read ($socket, 1024) or die("Could not read server response: 

[$errorcode] $errormsg"); 


            echo $resultserv;

            socket_close($socket);

        }

        ?>

Updated: I add socket_set_option(); still I get Fatal error in socket_read if it reads reaches 60 seconds.

Upvotes: 1

Views: 1903

Answers (1)

shannonman
shannonman

Reputation: 861

I have used this with success:

socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec" => 60, "usec" = >0));

That should give you a timeout of 60 seconds.

Upvotes: 1

Related Questions