Current Location: Home> Latest Articles> How to Prevent Blocking During the Connection Process with socket_addrinfo_connect

How to Prevent Blocking During the Connection Process with socket_addrinfo_connect

M66 2025-06-22

2. How to Prevent Blocking?

To avoid blocking, we can use several methods to control the connection process.

2.1 Set Non-Blocking Mode

By default, PHP sockets operate in blocking mode, meaning the program will stall during the connection process until the connection is successful or times out. We can avoid this blocking behavior by setting the socket to non-blocking mode.

socket_set_block($socket);  // Set to blocking mode  
socket_set_nonblock($socket);  // Set to non-blocking mode  

In non-blocking mode, the connection request will return immediately without waiting for the remote host's response. As a result, the program can continue executing other tasks. You can monitor the connection status using socket_select until the connection succeeds or fails.

$timeout = 5;  // Set timeout duration  
$start_time = time();  
while (true) {  
    if (time() - $start_time > $timeout) {  
        echo "Connection timed out\n";  
        break;  
    }  
if ($result) {  
    echo "Connection successful\n";  
    break;  
}  

// Retry after a short delay  
usleep(100000);  

}

2.2 Use socket_select for Multiplexing

If you need to handle multiple socket connections simultaneously, you can use socket_select to monitor the status of multiple sockets. This allows you to check multiple connections within a single loop, avoiding the blocking issue of each individual connection.

$read = array($socket);  
$write = null;  
$except = null;  
$timeout = 5;  // Set timeout  
<p>// Use socket_select for timeout and blocking detection<br>
$changed_sockets = socket_select($read, $write, $except, $timeout);</p>
<p>if ($changed_sockets === false) {<br>
echo "socket_select error\n";<br>
} elseif ($changed_sockets > 0) {<br>
// If connection is successful, handle the connection<br>
echo "Connection successful\n";<br>
} else {<br>
echo "Connection timed out\n";<br>
}<br>

By using socket_select, we can check whether a connection is successful in non-blocking mode, thereby avoiding the traditional blocking connection process.


3. Use stream_socket_client as an Alternative

In addition to directly using socket_addrinfo_connect, PHP also provides the stream_socket_client function to create and manage socket connections. stream_socket_client supports more advanced features and allows us to easily set timeouts and non-blocking modes.

$address = 'tcp://m66.net:80';  
$timeout = 5;  // Set timeout  
$context = stream_context_create(['socket' => ['timeout' => $timeout]]);  
$socket = stream_socket_client($address, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $context);  
<p>if ($socket === false) {<br>
echo "Connection failed: $errstr ($errno)\n";<br>
} else {<br>
echo "Connection successful\n";<br>
fclose($socket);<br>
}<br>

stream_socket_client not only supports non-blocking connections but also allows you to easily set connection timeouts through the timeout parameter, preventing long periods of blocking.


4. Set Appropriate Timeouts

Whether using socket_addrinfo_connect or stream_socket_client, it is important to set appropriate connection timeouts. If the remote host does not respond for an extended period, the program will wait indefinitely. To prevent this, setting a reasonable timeout mechanism is crucial.

When using socket_addrinfo_connect, we can monitor the connection progress and set a timeout to avoid long periods of blocking:

$timeout = 5;  // Timeout set to 5 seconds  
$start_time = time();  
while (time() - $start_time < $timeout) {  
    $result = socket_addrinfo_connect($socket, $address, $port);  
    if ($result) {  
        echo "Connection successful\n";  
        break;  
    }  
    usleep(100000);  // Wait a short time before retrying  
}  

If the connection time exceeds the predefined timeout, the program can actively terminate the connection to avoid getting stuck in an infinite wait state.