我看了几个教程,看了Symfony和Ratchet API文档,但我无法在我的聊天类(WebSocket服务器应用程序)中获得会话数据。
设置用户点击网页时的会话数据:
<?php
use SymfonyComponentHttpFoundationSessionSession;
use SymfonyComponentHttpFoundationSessionStorageHandler;
use SymfonyComponentHttpFoundationSessionStorageNativeSessionStorage;
use SymfonyComponentHttpFoundationSessionStorageHandlerMemcacheSessionHandler;
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 RatchetServerIoServer;
use RatchetHttpHttpServer;
use RatchetWebSocketWsServer;
use RatchetSessionSessionProvider;
use SymfonyComponentHttpFoundationSessionStorageHandler;
use MyAppChat;
$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 HandlerMemcacheSessionHandler($memcache)
);
$server = IoServer::factory(
new HttpServer(
new WsServer(
$session
)
),
$port,
$ip
);
$server->run();
在我的MyAppChat应用程序中,我试图获得我设置的会话数据,但它返回NULL
:
<?php
namespace MyApp;
use RatchetMessageComponentInterface;
use RatchetConnectionInterface;
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将不会同时发送到两台主机。
你可以通过将WebSocket设置为"hostname"而不是"127.0.0.1"来解决这个问题。那么它应该可以工作了:)