使用 Ratchet Websocket 和 Symfony 获取会话数据

Get session data using Ratchet Websocket and Symfony

我看了几个教程并查看了 Symfony 和 Ratchet API 文档,但我无法在聊天 class(WebSocket 服务器应用程序)中获取会话数据。

我设置了用户点击网页时的session数据:

<?php
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\Handler;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
use Symfony\Component\HttpFoundation\Session\Storage\Handler\MemcacheSessionHandler;

require 'vendor/autoload.php';

$memcache = new Memcache;
$memcache->connect('127.0.0.1', 11211);

$storage = new NativeSessionStorage(
    array(),
    new MemcacheSessionHandler($memcache)
);
$session = new Session($storage);
$session->start();
$session->set('id', $user_id);

print_r($session->all());
# Array ( [id] => 1 )

我通过命令行启动 WebSocket 服务器 (php ./server.php):

<?php
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use Ratchet\Session\SessionProvider;
use Symfony\Component\HttpFoundation\Session\Storage\Handler;
use MyApp\Chat;

$ip = "127.0.0.1";
$port = "8080";

# Change the directory to where this cron script is located.
chdir(dirname(__FILE__));

# Get database connection.
require_once '../../includes/config.php';
require_once '../../vendor/autoload.php';

$memcache = new Memcache;
$memcache->connect($ip, 11211);

$session = new SessionProvider(
    new Chat,
    new Handler\MemcacheSessionHandler($memcache)
);

$server = IoServer::factory(
    new HttpServer(
        new WsServer(
            $session
        )
    ),
    $port,
    $ip
);
$server->run();

在我的 MyApp\Chat 应用程序中,我尝试获取我设置的会话数据,但它 returns NULL:

<?php
namespace MyApp;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;

class Chat implements MessageComponentInterface
{
    protected $clients;
    private $dbh;

    public function __construct()
    {
        global $dbh;
        $this->clients=array();
        $this->dbh=$dbh;
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients[$conn->resourceId] = $conn;
        echo "New connection! ({$conn->resourceId})\n";

        print_r($conn->Session->get('name'));
        # NULL
    }
}

为了在服务之间传递会话,它们必须托管在同一域中。这是因为会话是通过 cookie 管理的,并且 cookie 是固定到特定域的。

在这种情况下,您的域不同,一个似乎托管在 "hostname" 上,另一个托管在“127.0.0.1”上。当它像这样设置时,您的 cookie 将不会发送到两个主机。

您可以通过在 "hostname" 而不是“127.0.0.1”上设置您的 WebSocket 来解决这个问题。然后它应该可以正常工作:)