Почемуто большинство примеров создания websocket сервера с использованием ratchet приведены без использования SSL. И у всех как я почитаю пляски с буном потом с проксированием через apache или ngnix. Но ведь он умеет и без этого!
Вот примерно как это оформляется:
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use React\EventLoop\Factory;
use React\Socket\SecureServer;
$loop = React\EventLoop\Factory::create();
$webSock = new React\Socket\Server('0.0.0.0:33423', $loop);
$webSock = new React\Socket\SecureServer($webSock, $loop, [
'local_cert' => 'sssss.crt',
'local_pk' => 'sssss.key',
'allow_self_signed' => TRUE,
'verify_peer' => FALSE
]);
$webServer = new Ratchet\Server\IoServer(
new Ratchet\Http\HttpServer(
new Ratchet\WebSocket\WsServer(
new MessageService($UsersApi)
)
),
$webSock,
$loop
);
$webServer->run();
А вот пример класса MessageService:
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();
}
}