1

这个文件运行我的服务器

<?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]:GET /send.php - 未捕获的错误:在 /home/ganbatte/Desktop/123/send.php:4 中的 null 上调用成员函数 push()

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

4

2 回答 2

0

此代码片段解释了 sendMessage() 并在范围内推送到 fds

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

参考:

Swoole 官方讨论

于 2021-07-07T17:13:28.320 回答
0

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

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

但是,鉴于也有一种sendMessage()方法,我想您可能应该使用它,但我对 swoole 并没有深入了解。

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

请记住,此 send 方法在 websocket 上向附加的客户端发送消息,而不是从客户端向服务器发送消息(客户端,很可能是浏览器,必须执行该部分)。

于 2020-01-03T22:17:33.723 回答