PHP 8.3.4 Released!

socket_set_nonblock

(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)

socket_set_nonblock设置套接字为非阻塞模式

说明

socket_set_nonblock(Socket $socket): bool

socket_set_nonblock() 为由 socket 参数指定的套接字设置 O_NONBLOCK 标记。

当一个操作(例如接收、发送、连接、接受连接……)在一个非阻塞套接字上执行时,脚本在接受到信号或操作处理完成前都不会暂停执行。如果操作会导致阻塞,被调用的函数将失败。

参数

socket

socket_create()socket_accept() 创建的 Socket 实例。

返回值

成功时返回 true, 或者在失败时返回 false

更新日志

版本 说明
8.0.0 现在 socketSocket 实例, 之前是 resource

示例

示例 #1 socket_set_nonblock() 示例

<?php
$socket
= socket_create_listen(1223);
socket_set_nonblock($socket);

socket_accept($socket);
?>

此示例在 1223 端口上创建了监听所有接口的套接字,并把此套接字设置为 O_NONBLOCK 模式。除非此时恰好有待处理的连接,否则 socket_accept() 将立即失败。

参见

add a note

User Contributed Notes 1 note

up
3
kpobococ at gmail dot com
14 years ago
Beware, when using this function within a loop (i.e. a demon with a socket). The socket_accept(), for example, emits a warning each time there is no incoming connection available to be read. My php error log file got huge in a matter of seconds, eventually crashing the server.

Of course, i used the @ before the function to take care of that problem.

[EDITOR: One can (and should) use socket_select to detect a new connection on a socket (it's a "readable" event)]
To Top