Reputation: 141
#!/usr/local/bin/php -q
<?
set_time_limit (0);
$address = '192.168.0.201';
$port = 1077;
$max_clients = 10;
$clients = Array();
$sock = socket_create(AF_INET, SOCK_STREAM, 0);
socket_bind($sock, $address, $port) or die('fail.');
socket_listen($sock);
while (true) {
$read[0] = $sock;
for ($i = 0; $i < $max_clients; $i++)
{
if ($client[$i]['sock'] != null)
$read[$i + 1] = $client[$i]['sock'] ;
}
$write=NULL;
$exceptions=NULL;
$ready = socket_select($read,$write,$exceptions,null);
if (in_array($sock, $read)) {
for ($i = 0; $i < $max_clients; $i++)
{
if ($client[$i]['sock'] == null) {
$client[$i]['sock'] = socket_accept($sock);
break;
}
elseif ($i == $max_clients - 1)
print ("many clients");
}
if (--$ready <= 0)
continue;
}
for ($i = 0; $i < $max_clients; $i++)
{
if (in_array($client[$i]['sock'] , $read))
{
$input = socket_read($client[$i]['sock'] , 1024);
if ($input == null) {
unset($client[$i]);
}
$n = trim($input);
if ($input == 'exit') {
socket_close($client[$i]['sock']);
} elseif ($input) {
$host = 'localhost';
$uname = 'root';
$pwd = 'taek0526';
$db = 'InputTest';
$con = mysql_connect($host,$uname,$pwd) or die("connection failed");
mysql_select_db($db,$con) or die("db selection failed");
mysql_query("set names utf8");
$data = explode(" ", $input);
mysql_query("INSERT INTO `test`(`data1`, `data2`) VALUES ('".$data[0]."', '".$data[1]."')");
mysql_close($con);
}
} else {
}
}
}
socket_close($sock);
?>
This is sample code about server.
When i test this code, have a problem. If client close program with out send "exit" client can not connect again so, I kill server process and restart; after that, client can connect again.
I think remain some data about previous connection.
How to check disconnect clients?
And then, how to remove data about disconnect clients?
for ($i = 0; $i < $max_clients; $i++) {
if( Check disconnect ){
disconnect work
}
}
I want to make code and add like this, but i don't no php function of socket.
Upvotes: 1
Views: 1291
Reputation: 19375
How to check disconnect clients?
You made this check already with this line:
if ($input == null) {
You just forgot to also insert
socket_close($client[$i]['sock']);
before
unset($client[$i]);
or you might want to combine
if ($input == null or trim($input) == 'exit')
{
socket_close($client[$i]['sock']);
unset($client[$i]);
And then, how to remove data about disconnect clients?
In addition to the above unset($client[$i])
you have to replace
$read[0] = $sock;
with
$read = Array($sock);
to clear array elements from the previous loop cycle.
Upvotes: 1