我查看了几个教程并查看了Symfony和Ratchet API文档,但我无法在Chat类(WebSocket服务器应用程序)中获取会话数据。
我在用户点击网页时设置了会话数据:
<?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 )
我通过命令行(php ./server.php
)启动WebSocket服务器:
<?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应用程序中,我尝试获取我设置的会话数据,但它返回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
}
}
答案 0 :(得分:1)
为了在类似服务之间传递会话,它们必须托管在同一个域中。这是因为会话通过cookie进行管理,并且cookie被固定到特定域。
在这种情况下,您的域名不同,其中一个似乎托管在&#34;主机名&#34;另一个在&#34; 127.0.0.1&#34;。如果设置如此,您的cookie将无法发送给两个主机。
您可以通过在&#34;主机名&#34;上设置WebSocket来解决此问题。而不是&#34; 127.0.0.1&#34;。那它应该工作:)