问题描述
我在 Laravel.io 上找到了一篇关于如何将 Laravel 会话加载到 Ratchet 中的帖子,该帖子已过时并使用 Laravel 5.4,因此我更改了一些内容以使其与 Laravel 8.x 一起使用
public function onopen(ConnectionInterface $conn)
{
// Attach connection
$this->clients->attach($conn);
// Create a new session handler for this client
$session = (new SessionManager(App::getInstance()))->driver();
// Get the cookies
$cookiesRaw = $conn->httpRequest->getHeader('Cookie');
$cookies = [];
if(count($cookiesRaw)) {
$cookies = Header::parse($cookiesRaw)[0]; // Array of cookies
}
// Get the laravel's one - todo: try catch
$sessionId = Crypt::decrypt(urldecode($cookies[Config::get('session.cookie')]),false);
var_dump($sessionId);
// Set the session id to the session handler
$session->setId($sessionId);
// Bind the session handler to the client connection
$conn->session = $session;
var_dump($conn->session->getId());
}
然后我也更改了发送消息,因为我收到了意想不到的结果。
public function onMessage(ConnectionInterface $conn,MessageInterface $msg)
{
$conn->session->start();
$sessionId = $conn->session->getId();
var_dump($sessionId);
if(!is_null(($decoded = json_decode(base64_decode($msg),true))) && array_diff(['message'],array_keys($decoded)))
return;
var_dump($decoded['message']);
return;
}
我用 JS 前端测试这个:
class WebRTC
{
socket;
constants;
timerId;
constructor(protocol,fqdns,port) {
this.constants = {
protocol: protocol,fqdns: fqdns,port: port
};
this.listenChanges();
}
listenChanges() {
this.socket = new WebSocket(`${this.constants.protocol}://${this.constants.fqdns}:${this.constants.port}`);
this.socket.onmessage = e => {
console.log(atob(e.data));
};
this.socket.onerror = () => {
this.socket.close();
};
this.socket.onopen = () => {
console.info('Connected to WebRTC Chat Server...');
this.socket.send(btoa(JSON.stringify({
message: '{{ session()->getId() }}' // Expected session
})));
clearInterval(this.timerId);
this.socket.onclose = () => {
this.timerId = setInterval(() => {
this.listenChanges();
},1000);
};
};
}
}
new WebRTC('ws','127.0.0.1','8080');
& 当连接打开时,我发送了 session()->getId()
,这是我需要的预期会话。但是,我在 CLI 中的输出是:
onopen() : $sessionId
string(81) "b0e41cf0d856bdfc8427e1fdde62d5a154519f9c|MLXa9H2BbnQmySt2hRB360UANxLGHyz6iRMxGcoG"
onopen() : $conn->session->getId()
string(40) "qyaDOQjNFlbrbjvvKRE1m5sN0dsGqqAsoMfkeqyU"
onMessage(): $conn->session->getId()
string(40) "qyaDOQjNFlbrbjvvKRE1m5sN0dsGqqAsoMfkeqyU"
JS 刀片格式的实际会话,作为消息发送
string(40) "MLXa9H2BbnQmySt2hRB360UANxLGHyz6iRMxGcoG"
在这里,我预期的 onMessage()
方法接收注入的依赖项 $conn
(ConnectionInterface) 和实际 ->session->getId()
的 session()->getId()
,因此我可以使 Auth::user()
工作.
对我做错了什么有什么想法吗?我按照 Laravel.Io 的要求尝试了 var_dump($conn->session->get(Auth::getName()));
,但它在 var_dump
上返回 null,并且我的用户已登录。
这应该让我可以使用 User::find() 或 Auth::user()。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)