你可以简单地调用the equivalent ofstream_set_timeout
使阻塞读和一定的超时后终止写道:
$s = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if (!socket_bind($s, '127.0.0.1', 0)) die("bind failed");
if (!socket_listen($s)) die("listen failed");
socket_getsockname($s, $localA, $localPort);
echo 'Listening on ' . $localA . ': ' . $localPort . "\n";
$c = socket_accept($s);
// Warning: Ugly hack ahead.
// This just mitigates the problem somewhat, and doesn't actually solve it
socket_set_option($c, SOL_SOCKET, SO_RCVTIMEO, array('sec'=>2,'usec'=>0));
socket_set_option($c, SOL_SOCKET, SO_SNDTIMEO, array('sec'=>2,'usec'=>0));
$r = socket_read($c, 1024);
echo 'read finished: got ' . var_export($r, true) . "\n";
注意,这是一个黑客攻击;恶意攻击者仍然可以每秒只发送1个字节左右。
而是投资于这些疯狂的黑客时,你真的应该切换到非阻塞IO或在一个单独的线程/进程处理接受的套接字。
请出示你的主循环 - 主要是您阻塞调用。 (例如'$海峡=与fgets($袜子);') – DaveRandom
http://ss.totalru.in/I5NG – Blake
这是失踪的我的代码的其余部分,因为它是非常广泛的,但是这是正在使用socket_read是哪里。值得注意的是套接字也在socket_close的循环中关闭。 – Blake