php 如何访问OpenSwoole WebSocket服务器中的会话数据?

kq0g1dla  于 2022-11-28  发布在  PHP
关注(0)|答案(1)|浏览(150)

我在OpenSwoole中实现了一个小型的WebSocket服务器。是否有办法访问用户的会话数据?我尝试了以下方法:

<?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";
});

当一个客户端连接时,它会显示:

# 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:

有没有办法从WebSocket服务器启动用户的PHP会话?用户会话本身是由Apache上托管的网站的PHP代码启动的。

sigwle7e

sigwle7e1#

看起来WebSocket服务器上的echo调用触发了“header already send”错误。

$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();
});

其次,必须使用apache的系统用户启动WebSocket服务器,以便访问会话数据:

# sudo -u www-data php websocket.php

相关问题