在循环客户端套接字数组时,如果套接字按原样回显,它会为每个客户端显示“resource id# 23”等不同的资源,但是当调用 socket_write 函数在每个循环中写入相同的回显消息时,写入功能失败,只有一个客户端得到写入的消息(ders一个输入框,如果你输入并提交,它会转到套接字服务器并为所有客户端写入d消息)
<form method='GET' action="">
<input type='text' name='name' />
<input type='submit' />
</form>
<?php
$no=500;$n=0;
$sock=null;
if(!($sock=socket_create(AF_INET,SOCK_STREAM,0)))
{
$code=socket_last_error();
$msg=socket_strerror($code);
die("ERROR $msg");
}
echo "Socket created $sock";
/*
$sock1=socket_create(AF_INET,SOCK_STREAM,0);
socket_set_option($sock1, SOL_SOCKET, SO_REUSEADDR, 1)
socket_connect($sock1,'localhost',9001);
if(sizeof($_GET)>0)
{
$msg=$_GET['name'];
if(!socket_send($sock1,$msg,strlen($msg),0))
{
$err=socket_last_error();
$emessg=socket_strerror($err);
die("ERROR $emessg");
}
}
*/
if (!socket_set_option($sock, SOL_SOCKET, SO_REUSEADDR, 1)) {
echo socket_strerror(socket_last_error($sock));
exit;
}
if(!socket_bind($sock, "127.0.0.1" , 9001) )
{
$cod=socket_last_error();
$msg=socket_strerror($cod);
die("ERROR:$msg");
}
echo "Socket BOund";
if(!socket_listen($sock,10))
{
$cod=socket_last_error();
$msg=socket_strerror($cod);
die("ERROR:$msg");
}
echo "Socket listen OK \n";
class clients{
public $addr=null,$portc=null,$soc=null;
function __construct($sock1) {
/*if(!($client[$n]=socket_create(AF_INET,SOCK_STREAM,0)))
{
$code=socket_last_error();
$msg=socket_strerror($code);
die("ERROR $msg");
}*/
$this->soc=$sock1;
if(socket_getpeername($this->soc,$address,$port))
{
echo "$address in port $port";
$this->addr=$address;
$this->portc=$port;
}
}
function sock(){return $this->soc;}
}//$client[500];
$client=array();
while(true){
//$client[$n++]=socket_accept($sock);
if($clienttemp=socket_accept($sock))
{
$client[$n]=new clients($clienttemp);
echo "NEw client ".$client[$n]->addr;
$n++;
//var_dump($client[$n-1]);
}
for($j=0;$j<$n;$j++)
//if($input=socket_read($client[$n-1]->soc,1024))
if($input=socket_read($client[$j]->soc,1024))
{
//$resp="<br/>****".$client[$n-1]->addr." says: $input*****";
$resp="<br/>****".$client[$j]->addr." says: $input*****";
if($input=='quit')break;
for($i=0;$i<$n;$i++)
{
socket_write($client[$i]->soc,$resp);
echo "****</br>$resp".$client[$i]->soc."****</br>";
}
}
// TO write in all clients
}
socket_close($client[$n-1]->soc);
socket_close($sock);
?>