php - Having problems adding a timeout to socket_connect() -
i'm sorry if has been asked before. i've looked everywhere can't find solution issue.
i have written socket client function project of mine, , add timeout doesn't take forever load if failed.
i've tried quite few things suggested docs , other answers on stackoverflow, nothing has worked far.
here's 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 following things;
set_time_limit()
- doesn't work. takes 20 seconds load shows "maximum execution time of..."ini_set("default_socket_timeout")
- still takes 20 seconds load.socket_set_nonblock()
- this works, makessocket_connect()
fail.- https://stackoverflow.com/a/16939666/3457242 - same above.
socket_set_nonblock()
makessocket_connect()
fail. socket_set_option()
- takes 20 seconds load. doesn't seem work.
the thing seems work socket_set_nonblock()
function, make socket_connect()
return false. can't figure out. appreciated.
thanks!
what while loop.
for example:
socket_set_nonblock($socket) or die("not able set socket nonblock"); $timeout = 5; $starttime = time(); while(!socket_connect($socket, $host, $port)) { if ((time() - $starttime ) >= $timeout) { die('timeout');
you current "socket_last_error" command in while loop. http://www.php.net/manual/en/function.socket-last-error.php
then, before time check if statement, error. if error 114 or 115, should time check error, otherwise can kill instantly error type. example, 100: network down.
Comments
Post a Comment