I'm sorry if this has been asked before. I've looked everywhere but can't find any solution to my issue.
I have written a socket client function for a project of mine, and I would like to add a timeout to it so it doesn't take forever to load if it failed.
I've tried quite a few things suggested by the docs and other answers on StackOverflow, but nothing has worked thus far.
Here's my function;
public function send($cmd, $host, $port){
if(!($socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Error (#300)");
}
if(!socket_connect($socket, $host, $port))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Error (#400)");
}
if(!socket_write($socket, $cmd, strlen($cmd)))
{
$errorcode = socket_last_error();
$errormsg = socket_strerror($errorcode);
die("Error (#301)");
}
$reply = socket_read($socket, 4096)
or die("Error (#302)");
socket_close($socket);
return $reply;
}
I've tried the following things;
set_time_limit()- Doesn't work. Takes 20 seconds to load but shows "Maximum execution time of..."ini_set("default_socket_timeout")- Still takes 20 seconds to load.socket_set_nonblock()- This works, but makessocket_connect()fail.- https://stackoverflow.com/a/16939666/3457242 - Same as above.
socket_set_nonblock()makessocket_connect()fail. socket_set_option()- Takes 20 seconds to load. Doesn't seem to work.
The only thing that seems to work is the socket_set_nonblock() function, but it always make socket_connect() return false. I just can't figure it out. Any help would be appreciated.
Thanks!