简体   繁体   English

如何访问OpenSwoole WebSocket服务器中的session数据?

[英]How to access session data in OpenSwoole WebSocket server?

I have a small websocket server implemented in OpenSwoole.我有一个用 OpenSwoole 实现的小型 websocket 服务器。 Is there a way to access the users session data?有没有办法访问用户 session 数据? I tried this:我试过这个:

<?php

use Swoole\WebSocket\Server;
use Swoole\Http\Request;
use Swoole\WebSocket\Frame;

$server = new Server("0.0.0.0", 9502);

$server->on("Start", function(Server $server)
{
    echo "Swoole WebSocket Server is started at http://127.0.0.1:9502\n";
});

$server->on('Open', function(Server $server, Swoole\Http\Request $request)
{
    echo "connection open: {$request->fd}\n";
    var_dump($request->cookie);
    echo "using session id ".$request->cookie['PHPSESSID']."\n";
    session_id(trim($request->cookie['PHPSESSID']));
    session_start();
    echo "user: ".$_SESSION['id_user'];
});
$server->on('Message', function(Server $server, Frame $frame)
{
    echo "received message: {$frame->data}\n";
   
    $server->push($frame->fd, json_encode(["hello", time()]));
});

$server->on('Close', function(Server $server, int $fd)
{
    echo "connection close: {$fd}\n";
});

$server->on('Disconnect', function(Server $server, int $fd)
{
    echo "connection disconnect: {$fd}\n";
});

which gives me this when a client connects:当客户端连接时,这给了我这个:

# php websocket.php 
Swoole WebSocket Server is started at http://127.0.0.1:9502
connection open: 1
array(1) {
  ["PHPSESSID"]=>
  string(26) "humr1mg4s26jp5fqkavih6tutf"
}
using session id humr1mg4s26jp5fqkavih6tutf
PHP Warning:  session_id(): Session ID cannot be changed after headers have already been sent in websocket.php on line 19
PHP Warning:  session_start(): Session cannot be started after headers have already been sent in websocket.php on line 20
PHP Warning:  Undefined variable $_SESSION in websocket.php on line 21
PHP Warning:  Trying to access array offset on value of type null in websocket.php on line 21
user:

Is there a way to start the users PHP session from the websocket server?有没有办法从 websocket 服务器启动用户 PHP session? The users session itself is started by the website's PHP code hosted on Apache.用户 session 本身是由托管在 Apache 上的网站代码 PHP 启动的。

Looks like the echo calls on the websocket server trigger the "header already send" errors.看起来 websocket 服务器上的echo显调用触发了“标头已发送”错误。 Using this works:使用这个作品:

$server->on('Open', function(Server $server, Swoole\Http\Request $request)
{
    session_id(trim($request->cookie['PHPSESSID']));
    session_start();
    // Do something ... and close the session afterwards.
    session_write_close();
});

Second, the websocket server has to be started using apache's system user for having access to the session data:其次,必须使用 apache 的系统用户启动 websocket 服务器才能访问 session 数据:

# sudo -u www-data php websocket.php

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM