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()
是。您的插座互动code将需要以不同的写入,兼顾特殊含义的错误codeS 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同步插座轮询循环有所一些,虚构样本code,根据要求:
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屋!