0

Ever 60 seconds, I wish to perform some other routine. During this event, I also wish to take the opportunity to reestablish connection if it drops for whatever reasons. How can this be accomplished?

<?php
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, "123.321.123.321" , 20);
socket_listen ($sock , 10);
while (true) 
{

    //Do some other routine ever 60 seconds

    $client =  socket_accept($sock);  //Blocking function!
    $input = socket_read($client, 1024000);
    $response=processInput($input);
    socket_write($client, $response);
}
user1032531
  • 24,767
  • 68
  • 217
  • 387
  • Check out this post: http://stackoverflow.com/questions/9793566/php-socket-server-check-if-client-is-alive – Revent Oct 25 '16 at 22:28
  • @Revent Thanks. It doesn't address the timeout question, but it does addressing recognizing when communication is lost. Maybe just have two independent programs? One a 60 second loop (or cron or whatever), and the second similar that I showed? – user1032531 Oct 25 '16 at 22:31
  • Here is a post about that topic, but I'm not sure how useful this will really be to your specific case: http://stackoverflow.com/questions/8310487/start-and-stop-a-timer-php. If I were in your shoes I would look into running the listener as a daemon or something. – Revent Oct 25 '16 at 22:46
  • Thanks again Revent, Yea, doesn't seem like a really good fit. I know it is off topic, but do you mind pointing me in the right direction how to run a listener as a daemon? It seems like the way to go, but I don't know where to start. – user1032531 Oct 25 '16 at 22:58

1 Answers1

0

use the stream_select() function.

for example:

$socket = stream_socket_server("tcp://0.0.0.0:8160", $errno,$errorMessage);
$master[] = $socket;
$read = $master;
$write_something = false;
$mod_fd = stream_select($read, $_w, $_e, $write_something ? 0 : 1, 5000);
LF00
  • 27,015
  • 29
  • 156
  • 295