(PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8)
socket_set_nonblock — ソケットリソースを非ブロックモードに設定する
socket_set_nonblock() 関数は、
socket パラメータで指定したソケットに
O_NONBLOCK フラグを設定します。
受信や送信、接続、待機といった操作を非ブロックモードのソケットに対して行うと、 その処理が完了するか何らかのシグナルを受信するまではスクリプトは停止しません。 また、その操作がブロックされると、呼び出し元の関数は失敗します。
| バージョン | 説明 |
|---|---|
| 8.0.0 |
socket は、Socket クラスのインスタンスになりました。
これより前のバージョンでは、リソース型でした。
|
例1 socket_set_nonblock() の例
<?php
$socket = socket_create_listen(1223);
socket_set_nonblock($socket);
socket_accept($socket);
?>
この例は、すべてのインターフェイス上でポート 1223
を待ち受けるソケットを作成し、それを O_NONBLOCK
モードに設定します。
socket_accept() は、
その時点で待機中の接続がない場合はすぐに失敗します。
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)]