【发布时间】:2014-06-07 11:47:21
【问题描述】:
我在网上搜索了很多,但没有找到有用的线索。
我有一个 websocket 服务器和一个 web 服务器在我的本地机器上一起运行。
当客户端使用浏览器 API 'new WebSocket("ws://localhost")' 连接到 websocket 服务器时,我需要将 $_SESSION 数据传递给它(请求使用反向代理发送到 websocket,它在收到带有“升级”标头的请求时知道它)。
关键是客户端成功连接到 ws 服务器,但我还需要使用 HTTP Web 服务器设置的 $_SESSION 变量恢复它们的 SESSION 数据。
其实我的情况是这样的(我用的是Ratchet库):
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
use MyApp\MyAppClassChat;
require dirname(__DIR__) . '/vendor/autoload.php';
$server = IoServer::factory(new HttpServer(new WsServer(new MyAppClass())), 8080);
$server->run();
MyAppClass 非常简单:
<?php
namespace MyAppClass;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
class MyAppClass implements MessageComponentInterface {
protected $clients;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
/* I would like to put recover the session infos of the clients here
but the session_start() call returns an empty array ($_SESSION variables have been previuosly set by the web server)*/
session_start();
var_dump($_SESSION) // empty array...
echo "New connection! ({$conn->resourceId})\n";
}
public function onMessage(ConnectionInterface $from, $msg) {
$numberOfReceivers = count($this->clients) -1;
echo sprintf('Connection %d sending message "%s" to %d other connection%s' . "\n", $from->resourceId, $msg,
$numberOfReceivers, $numberOfReceivers == 1 ? '' : 's');
$this->clients->rewind();
while ($this->clients->valid())
{
$client = $this->clients->current();
if ($client !== $from) {
$client->send($msg);
}
$this->clients->next();
}
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
echo "Connection {$conn->resourceId} has disconnected\n";
}
public function onError(ConnectionInterface $conn, \Exception $e) {
echo "An error has occurred: {$e->getMessage()}\n";
$conn->close();
}
}
有没有办法用我的实际布局来做到这一点,或者我应该配置 apache 以便使用 mod_proxy_wstunnel 模块?
感谢帮助!!!
【问题讨论】:
标签: php apache session websocket