PHP 可以异步使用套接字吗? [英] Can PHP asynchronously use sockets?
问题描述
典型的 PHP 套接字功能是同步的,并在等待传入连接和数据时暂停线程.(例如.socket_read
和 socket_listen
)
Typical PHP socket functionality is synchronous, and halts the thread when waiting for incoming connections and data. (eg. socket_read
and socket_listen
)
我如何异步执行相同的操作?所以我可以在数据接收事件中响应数据,而不是轮询数据等.
How do I do the same asynchronously? so I can respond to data in a data received event, instead of polling for data, etc.
推荐答案
是的,这就是 socket_set_nonblock()
的用途.考虑到错误代码 11、EWOULDBLOCK
和 115、EINPROGRESS
所假定的特殊含义,您的套接字交互代码需要以不同方式编写.
Yup, that's what socket_set_nonblock()
is for. Your socket interaction code will need to be written differently, taking into account the special meanings that error codes 11, EWOULDBLOCK
, and 115, EINPROGRESS
, assume.
以下是一些来自 PHP 同步套接字轮询循环的虚构示例代码,应要求提供:
Here's some somewhat-fictionalized sample code from a PHP sync socket polling loop, as requested:
$buf = '';
$done = false;
do {
$chunk = socket_read($sock, 4096);
if($chunk === false) {
$error = socket_last_error($sock);
if($error != 11 && $error != 115) {
my_error_handler(socket_strerror($error), $error);
$done = true;
}
break;
} elseif($chunk == '') {
$done = true;
break;
} else {
$buf .= $chunk;
}
} while(true);
这篇关于PHP 可以异步使用套接字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!