Вот моя реализация
<?php
namespace chatting;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class Chat implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
//store the new connection
$this->clients->attach($conn);
echo "{$conn->resourceId} someone connected\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
//$client->send("Privet");
//send the message to all the other clients except the one who sent.
$json = (json_decode($msg,true)); // {"userID":"#", "sendTo":"#", "message":"lorem"}
$msg = $json['message'];
$tosendid = $json['sendTo'];
//print_r($this->clients);
foreach ($this->clients as $client) {
if ($tosendid == $client->resourceId) {
$client->send($msg);
}else{
$client->send($client->resourceId . ' ' . $tosendid . ' ' . $msg );
}
/* foreach ($this->clients as $client) {
if ($from !== $client) {
$client->send($msg);
}*/
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "{$conn->resourceId} someone has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
Запуск сервера
require '../vendor/autoload.php';
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use chatting\Chat;
$server = IoServer::factory(
new HttpServer(
new WsServer(
new Chat()
)
),
80,
);
$server->run();
Есть готовые библиотеки которых реализована отправка приватных сообщения(можно на node.js)