Function name: socket_set_nonblock()
Applicable version: PHP 4 >= 4.1.0, PHP 5, PHP 7
Usage: socket_set_nonblock(resource $socket)
Function Description: The socket_set_nonblock() function marks the given socket as non-blocking mode, which means that the process does not block when reading and writing data.
parameter:
Return value: Return true on success, and false on failure.
Example:
<?php // 创建套接字$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); // 设置套接字为非阻塞模式if (socket_set_nonblock($socket)) { echo "套接字设置为非阻塞模式成功!\n"; } else { echo "套接字设置为非阻塞模式失败!\n"; } // 连接到服务器if (socket_connect($socket, '127.0.0.1', 8080) === false) { // 非阻塞模式下,连接可能会立即返回失败$error = socket_last_error($socket); if ($error != SOCKET_EINPROGRESS && $error != SOCKET_EALREADY) { echo "连接服务器失败:" . socket_strerror($error) . "\n"; } else { echo "连接正在进行中...\n"; } } // 读取数据$data = socket_read($socket, 1024); if ($data === false) { // 非阻塞模式下,如果没有数据可读取,会立即返回false $error = socket_last_error($socket); if ($error != SOCKET_EAGAIN) { echo "读取数据失败:" . socket_strerror($error) . "\n"; } else { echo "没有可读取的数据。\n"; } } // 写入数据$message = "Hello, Server!"; if (socket_write($socket, $message, strlen($message)) === false) { // 非阻塞模式下,如果无法立即写入数据,会立即返回false $error = socket_last_error($socket); if ($error != SOCKET_EAGAIN) { echo "写入数据失败:" . socket_strerror($error) . "\n"; } else { echo "无法立即写入数据。\n"; } } // 关闭套接字socket_close($socket); ?>
In the above example, we first create a socket and then use the socket_set_nonblock() function to set the socket to non-blocking mode. Next, we try to connect to the server. If the connection fails, we will determine whether the connection is in progress based on the error code. Then, we try to read the data. If there is no readable data, we will judge whether there is no data to read based on the error code. Finally, we try to write data. If the data cannot be written immediately, we will judge whether it cannot be written immediately based on the error code. Finally, we close the socket.
Note that in non-blocking mode, some operations may return immediately instead of blocking waiting. Therefore, you need to handle the corresponding situation based on the return value or error code.