socket_accept with timeout, seems to work for me on Apache/1.3.37 (FreeBSD 6.0) PHP/4.4.7.
Adapted from ScriptBlue at nyc dot rr dot com's post under socket_connect.
<?php
$socket = socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
socket_bind($socket,$address,$port);
socket_listen($socket);
echo "Waiting for a connection\n";
$conn = false;
switch(@socket_select($r = array($socket), $w = array($socket), $e = array($socket), 60)) {
case 2:
echo "Connection refused\n";
break;
case 1:
echo "Connection accepted\n";
$conn = @socket_accept($socket);
break;
case 0:
echo "Connection timed out\n";
break;
}
if ($conn !== false) {
// communicate over $conn
}
?>
socket_accept
(PHP 4 >= 4.0.7, PHP 5)
socket_accept — ソケットへの接続を許可する
説明
resource socket_accept
( resource $socket
)
socket_create() を使用してソケット socket を作成した後、 socket_bind() で名前に関連付け、 socket_listen() で接続をモニタします。この関数は、 このソケットへの接続を許可します。接続に成功すると、新規の ソケット記述子が返されます。この記述子は通信の際に使用されます。 ソケット上に複数の接続がキューで待っている場合、最初の接続が使用 されます。接続待ちがない場合、socket_accept() は接続が存在するまでブロックされます。 socket が socket_set_blocking() または socket_set_nonblock() により非ブロックモードで 作成された場合、FALSE が返されます。
socket_accept() により返されたソケットリソースは、 新規接続を許可するために使用することはできません。この場合でも 元の接続待ちのソケット socket は オープンされたままであり、再使用可能です。
返り値
成功した場合に新規ソケットリソースを、エラー時に FALSE を返します。 実際のエラーコードは、socket_last_error() を コールすることで取得可能です。このコードを socket_strerror() に渡すことで、 エラーの内容を文字列で取得することが可能です。
socket_accept
galantonp at yahoo dot com
14-Jun-2007 02:20
14-Jun-2007 02:20
gmkarl at gmail dot com
23-May-2007 01:15
23-May-2007 01:15
Be aware signal handler functions set with pcntl_signal are not called while a socket is blocking waiting for a connection; the signal is absorbed silently and the handler called when a connection is made.
simon at 180solutions dot com
17-May-2005 12:11
17-May-2005 12:11
>Accepting a connection using php-sockets:
>
>$fd = socket_create(AF_INET, SOCK_STREAM, 6 /* OR >getprotobyname("TCP")*/);
>
>$PORT = 5000;
>
>socket_bind($fd, "0.0.0.0", $PORT);
>
>while(true)
>{
>$remote_fd = socket_accept($fd);
>
>remote_socket_client_handle($remote_fd);
>
>}
>
>It is simple!
This example doesn't work. You have to call socket_listen($fd) after your bind in order to accept incoming connections.
Simon
Greg MacLellan
12-Dec-2003 05:49
12-Dec-2003 05:49
The socket returned by this resource will be non-blocking, regardless of what the listening socket is set to. This is actually true for all FCNTL modifiers.
diogo at transoft dot com dot br
19-Aug-2003 05:32
19-Aug-2003 05:32
Accepting a connection using php-sockets:
$fd = socket_create(AF_INET, SOCK_STREAM, 6 /* OR getprotobyname("TCP")*/);
$PORT = 5000;
socket_bind($fd, "0.0.0.0", $PORT);
while(true)
{
$remote_fd = socket_accept($fd);
remote_socket_client_handle($remote_fd);
}
It is simple!