class MessageService implements MessageComponentInterface {
protected $clients;
public $cnt=0;
public $uapi="";
public function __construct($uu) {
$this->uapi=$uu;
$this->clients = array();
echo "- запустили, ждем соединения..\n";
}
public function onOpen(ConnectionInterface $conn) {
$user["user"]="";
$user["conn"]=$conn;
$this->clients[]=$user;
$this->cnt++;
echo "--с нами ".count($this->clients)."\n";
echo "---спрашиваю who_are_you?\n";
$conn->send(json_encode(array("command"=>"who_are_you")));
}
public function onMessage(ConnectionInterface $from, $msg) {
echo "-- пришло сообщение: $msg \n";
$msg= json_decode($msg);
//var_dump($msg);
if (isset($msg->command)):
switch ($msg->command) {
case "who_am_i":
// обхожу все соединения, и добавляю параметр - пришедший id пользователя
foreach ($this->clients as &$client) {
if ($from == $client["conn"]) {
$client["user"]=$msg->user;
};
};
break;
default:break;
}
endif;
}
public function onClose(ConnectionInterface $conn) {
$user="";
foreach ($this->clients as $key=>$client) {
if ($client["conn"]==$conn):
echo "-- ушел $key(".$client["user"].")\n";
$user=$client["user"];
unset($this->clients[$key]);
endif;
};
echo "-- осталось соединений ".count($this->clients)."\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}