After many non-sleep nights I got the most simple multi-client server written in PHP that really works. Ctrl+C and Ctrl+V... use as command line to test it. Enjoy it.
<?php
ini_set('error_reporting', E_ALL ^ E_NOTICE);
ini_set('display_errors', 1);
set_time_limit (0);
$address = '10.203.9.67';
$port = 6901;
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, $address, $port) or die('Could not bind to address');
socket_listen($sock);
socket_set_nonblock($sock);
while (true)
{
unset($read);
$j = 0;
if (count($client))
{
foreach ($client AS $k => $v)
{
$read[$j] = $v;
$j++;
}
}
$client = $read;
if ($newsock = @socket_accept($sock))
{
if (is_resource($newsock))
{
socket_write($newsock, "$j>", 2).chr(0);
echo "New client connected $j";
$client[$j] = $newsock;
$j++;
}
}
if (count($client))
{
foreach ($client AS $k => $v)
{
if (@socket_recv($v, $string, 1024, MSG_DONTWAIT) === 0)
{
unset($client[$k]);
socket_close($v);
}
else
{
if ($string)
{
echo "$k: $string\n";
}
}
}
}
sleep(1);
}
socket_close($sock);
?>