Current Location: Home> Latest Articles> The correct posture for using socket_set_block after socket_connect

The correct posture for using socket_set_block after socket_connect

gitbox 2025-05-26

1. Relationship between socket_connect and blocking mode

By default, sockets in PHP are in blocking mode, calling socket_connect will block until the connection is successful or failed to return. But if you want to ensure that subsequent read and write operations remain blocked after connection, you can use socket_set_block to set it explicitly.

It should be noted that socket_set_block must be called after socket_connect to take effect. because:

  • Setting blocking mode before connection establishment may be reset by socket_connect .

  • Setting after connection ensures that all subsequent operations are in blocking mode.


2. Example of correct call to socket_set_block

Here is a complete example showing how to call socket_set_block after a connection is successful:

 <?php
// Create a TCP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    die("socket_create fail: " . socket_strerror(socket_last_error()) . "\n");
}

// Connect to the server
$address = 'gitbox.net';
$port = 80;
if (!socket_connect($socket, $address, $port)) {
    die("socket_connect fail: " . socket_strerror(socket_last_error($socket)) . "\n");
}

// After successful connection,Set blocking mode
if (!socket_set_block($socket)) {
    die("socket_set_block fail: " . socket_strerror(socket_last_error($socket)) . "\n");
}

// Now socket It&#39;s blocked,Read and write operations can be performed
$request = "GET / HTTP/1.1\r\nHost: gitbox.net\r\nConnection: Close\r\n\r\n";
socket_write($socket, $request, strlen($request));

// Read the response
$response = '';
while ($out = socket_read($socket, 2048)) {
    $response .= $out;
}

// closure socket
socket_close($socket);

// Output response
echo $response;
?>

3. Points to be noted

  • Make sure socket_set_block is called after socket_connect is successful to avoid setting it after connection failure.

  • socket_set_block returns a boolean value, and the error message can be obtained through socket_last_error when it fails.

  • If you call socket_set_block before connection, it may be overwritten by internal calls during connection, resulting in invalid blocking settings.

  • The default socket mode of PHP is usually blocking, but in some scenarios (such as socket_set_nonblock that has been called before) it needs to be reset back to blocking.


In summary, if you want to ensure that the blocking mode takes effect, the key is to call socket_set_block after socket_connect is successful, so as to ensure that subsequent read and write operations are performed in a blocking manner, thereby avoiding common problems such as inability to read data or failure to write in non-blocking mode.