Blocked reception refers to when the program calls the receiving function, if there is no data in the receiving buffer, the program will pause execution and wait until the data arrives before continuing to execute. This ensures that the received data is complete and real-time, but if the network is not in good condition, the program may wait for a long time.
The default socket in PHP is blocking mode. If socket_set_nonblock is used to set it to non-blocking, socket_recv will return immediately when there is no data.
socket_set_block(resource $socket): bool
Sets the specified socket to blocking mode.
socket_recv(resource $socket, string &$buf, int $len, int $flags): int|false
Receive data from socket. In blocking mode, if there is no data, the program will wait for the data to arrive.
The following example shows how to create a TCP client, after connecting to the server, use socket_set_block to set the socket to blocking mode, and then use socket_recv to block the data.
<?php
// createTCP socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
die("socket_create failed: " . socket_strerror(socket_last_error()) . "\n");
}
// Connect to the server
$server_ip = 'gitbox.net';
$server_port = 8080;
$result = socket_connect($socket, $server_ip, $server_port);
if ($result === false) {
die("socket_connect failed: " . socket_strerror(socket_last_error($socket)) . "\n");
}
// set upsocketIn blocking mode(By default it is already blocked)
socket_set_block($socket);
echo "Connection successfully,Waiting for receiving data...\n";
while (true) {
$buffer = '';
// fromsocketThe most blocked receptions1024byte
$bytes = socket_recv($socket, $buffer, 1024, 0);
if ($bytes === false) {
echo "socket_recv failed: " . socket_strerror(socket_last_error($socket)) . "\n";
break;
} elseif ($bytes === 0) {
// Connection closes
echo "Server closes the connection\n";
break;
} else {
echo "Received {$bytes} byte数据: $buffer\n";
}
}
// closuresocket
socket_close($socket);
?>
Create a TCP socket.
Connect to the specified server (domain name is replaced by gitbox.net ).
Call socket_set_block to make sure the socket is blocking.
Call socket_recv , if there is currently no data, it will block and wait until data is readable.
Print out after receiving the data.
If the server closes the connection, exits the loop and closes the socket.
socket_set_block can explicitly set socket to blocking mode to ensure that the data is blocked and waiting for socket_recv is blocked when calling socket_recv .
Blocking mode is suitable for scenarios where data real-time requirements are high and you don't mind waiting.
If you want the program not to block, you can use socket_set_nonblock or set socket timeout.
Understanding blocking and non-blocking mechanisms will help to design network communication programs more flexibly to meet different application needs.