如何在swoole(php的websocket扩展)上将消息从php发送到浏览器?



这个文件运行我的服务器

<?php
class websocket
{
public $ws;
public function start()
{
$this->ws = new swoole_websocket_server('127.0.0.1', 9502);
$this->ws->on('open', function ($ws, $request) {
echo "connection open: {$request->fd}n";
});
$this->ws->on('message', function ($ws, $frame) {
echo "received message: {$frame->data}n";
$this->ws->push($frame->fd, json_encode(["hello", "world"]));
});
$this->ws->on('close', function ($ws, $id) {
$this->onClose($id);
});
$this->ws->start();
$this->sendMessage(1, "asdfasdf");
}
public function sendMessage($id,$msg)
{
$this->ws->push($id, "asdf");
}
}

我像这样从 cli 运行它:

php -r 'include("websocket.php"); $web = new websocket; $web->start();' 

然后我在浏览器上打开这个文件

<?php
include ('websocket.php');
$n = new websocket();
$n->ws->push(1, "asdf",  1,  true);

我收到此错误:

127.0.0.1:51180 [500]:获取/发送.php - 未捕获的错误:在/home/ganbatte/Desktop/123/send.php:4 中调用 null 的成员函数 push((

为什么会这样,我该如何解决?

在实例化对象之后,$ws属性还没有任何值。然而,您尝试访问它。看起来您必须先启动它,如下所示:

include ('websocket.php');
$n = new websocket();
$n->start(); // <-- add this line
$n->ws->push(1, "asdf",  1,  true);

但是,鉴于也有sendMessage()方法,我想您可能应该使用它,但我根本不深入研究 swoole。

这看起来像您正在寻找的文档:开始使用 Swoole 也许在那里阅读系统基础知识也是一个好主意。

请记住,此发送方法将消息"在"websocket 上发送到连接的客户端,而不是从客户端发送到服务器(客户端,很可能是浏览器,必须执行该部分(。

这个代码片段解释了 sendMessage(( 和 push to fds in scopes

`$server->fds = [];
$server->on('open', function (swoole_websocket_server $server, $request) 
{
// add fd to scope
$server->fds[$request->fd] = true; // dummy-bool
});

$server->on('close', function ($server, $fd) {
// delete fd from scope
unset($server->fds[$fd]);
});
$server->on('message', function (swoole_websocket_server $server, $frame) 
{
$message = "simple test message number: " . rand(1,10000);
// pipe the message to all 9 other workers
for ($i=0; $i < 10; $i++) { // WORKER_NUM
if ($i !== $server->worker_id)
// in this case only workers (no taskworkers)
$server->sendMessage($message, $i); 
}
// message to all fds in this scope
testMessageSender($server, $message);
});
$server->on('pipeMessage', function($server, $src_worker_id, $data) {
// send to your known fds in worker scope
testMessageSender($server, $data);
});
function testMessageSender(&$server, $message){
// use only your own scope fds
foreach ($server->fds as $fd => $dummyBool) {
// push to your connected clients
$server->push($fd, $message);
}
}`

参考:

斯伍尔官方讨论

最新更新