I'm reusing socket code from other sources to produce a server that listens on a port, receives a string, and returns a result code. I'm good on everything EXCEPT getting an open socket to timeout:
snippet
I can see in the php manual that the "streams" methdology would have supported timeout on the child, but this socket approach may not
I could easily store and compare the child socket target expiration time, but I'm not sure if I can break out of the "read" loop to check the timeout/expiration every second.
D.E.R. Management - IT Project Management Consulting
snippet
Code:
#!/usr/bin/php -q
<?php
error_reporting(1);
ini_set('display_errors', '1');
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
$max_clients = 50;
socket_set_option($socket, SOL_SOCKET, SO_REUSEADDR, 1);
socket_bind($socket, 0, 999);
socket_listen($socket, $max_clients);
$clients = array('0' => array('socket' => $socket));
while(TRUE)
{
$read[0] = $socket;
for($i=1; $i<count($clients)+1; ++$i)
{
if($clients[$i] != NULL)
{ $read[$i+1] = $clients[$i]['socket'];
}
}
$ready = socket_select($read, $write = NULL, $except = NULL, $tv_sec = NULL);
if(in_array($socket, $read))
{
for($i=1; $i < $max_clients+1; ++$i)
{
if(!isset($clients[$i]))
{
$clients[$i]['socket'] = socket_accept($socket);
socket_getpeername($clients[$i]['socket'],$ip);
$clients[$i]['ipaddy'] = $ip;
socket_write($clients[$i]['socket'], 'Client'.(count($clients) - 1).':'."\r\n");
break;
}
elseif($i == $max_clients - 1)
{
echo 'To many Clients connected!'."\r\n";
}
if($ready < 1)
{
continue;
}
}
}
for($i=1; $i<$max_clients+1; ++$i)
{
if(in_array($clients[$i]['socket'], $read))
{
$data = @socket_read($clients[$i]['socket'], 1024, PHP_NORMAL_READ);
if($data === FALSE)
{
unset($clients[$i]);
continue;
}
$data = trim($data);
if(!empty($data))
{
$returnresult=0;
if($data == 'exit')
{
socket_write($clients[$i]['socket'], 'goodbye'."\n");
# echo 'Client ',$i,' is exiting.',"\n";
unset($clients[$i]);
continue;
}
I can see in the php manual that the "streams" methdology would have supported timeout on the child, but this socket approach may not
I could easily store and compare the child socket target expiration time, but I'm not sure if I can break out of the "read" loop to check the timeout/expiration every second.
D.E.R. Management - IT Project Management Consulting