Non-blocking socket connection
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function nonblock_socket_connect($ip, $port) | |
{ | |
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); | |
if (!socket_set_nonblock($socket)) { | |
socket_error($socket); | |
} | |
$connected = @socket_connect($socket, $ip, $port); | |
if (!$connected) { | |
// http://php.net/manual/en/function.socket-connect.php#refsect1-function.socket-connect-returnvalues | |
// If the socket is non-blocking then socket_connect() function returns FALSE with an error Operation now in progress. | |
$in_progress = (strpos(socket_strerror(socket_last_error()), 'in progress') !== false); | |
if (!$in_progress) { | |
socket_error($socket); | |
} | |
} | |
return $socket; | |
} | |
function socket_error($socket) | |
{ | |
$errno = socket_last_error($socket); | |
$errstr = socket_strerror($errno); | |
throw new Exception($errstr, $errno); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment