I am trying to set a timeout on my php function below to avoid the page load taking a while, but I need to send a tcp message over to an ip and port via php on page load, how can I set a timeout incase the ip and port is unreachable?
I have tried using the socket_set_option method below but unfortinately it will takes up to 30 seconds, sometimes longer.
I use this in a laravel 5.2 project
public static function send($command, $data = '')
{
$MUSdata = $command . chr(1) . $data;
$socket = \socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp'));
$connect_timeval = array(
"sec"=>0,
"usec" => 100
);
\socket_set_option(
$socket,
SOL_SOCKET,
SO_SNDTIMEO,
$connect_timeval
);
\socket_connect($socket, Config::get('frontend.client_host_ip'), Config::get('frontend.mus_host_port'));
\socket_send($socket, $MUSdata, strlen($MUSdata), MSG_DONTROUTE);
\socket_close($socket);
}
SO_SNDTIMEOdoes not affect the connection timeout; only write operations after the socket is connected. You will need to put the socket in nonblocking mode, write your own timeout loop for the connect (which will return EAGAIN until the socket connects), and then put the socket back into blocking mode. I'd post this as an answer but I'm not sure offhand if PHP supports that.