我试图根据Workerman编写游戏服务器。
主要思想是:工作人员列表接受来自客户端的消息并将其放入队列(RabbitMQ),另一组工作人员从队列中获取消息,进行一些计算并相应地更新GameWorld实例。
GameWorld实例本身是在主进程启动时创建的,在创建GameWorld对象后创建工作程序。所以,我写了虚拟类服务器:
namespace Server;
use \Workerman\Worker;
use \Workerman\Lib\Timer;
class Server {
private $name;
public function setName(string $name){
$this->name = $name;
}
public function printName(){
echo $this->name;
}
}
此外,我写了两个简单的工作程序,仅用于测试从不同工作者更新对象的概念。
首先(start_worker1.php
):
use \Workerman\Worker;
use \Workerman\Lib\Timer;
use \Server\Server;
global $ws_worker;
$ws_worker = new Worker('Websocket://0.0.0.0:8000');
$ws_worker->name = 'FirstWorker';
$ws_worker->onWorkerStart = function($ws_worker)
{
$ws_worker->server = new Server();
$ws_worker->server->setName("FirstName");
echo "worker1 started\n";
$ws_worker->is_started = TRUE;
var_dump($ws_worker);
};
在这里,我创建了新的Server对象并为其命名,并将属性$ws_worker->is_started
更改为TRUE(默认值为False)。
秒(start_worker2.php
):
use \Workerman\Worker;
use \Workerman\Lib\Timer;
global $ws_worker;
$worker = new Worker('Websocket://0.0.0.0:8001');
$worker->name = 'SecondWorker';
// here I'm checking, if I had an object of the first worker
// and actually it outputs all the data about first worker object,
// but $ws_worker->server is NULL and $ws_worker->is_started = FALSE
// This is confusing me so much..
var_dump($ws_worker);
// here I'm trying to detect when first worker is started
// but it return false all the time..
while(!$ws_worker->is_started){
var_dump($ws_worker->is_started);
sleep(1);
}
$worker->onWorkerStart = function() use($ws_worker){
echo "worker2 started\n";
var_dump($ws_worker);
$ws_worker->sever->setName("NewName");
};
这里我创建了第二个worker,并尝试访问第一个worker对象的server
属性,但没有成功..
所有这些东西都是这样开始的:
use Workerman\Worker;
use Server\Server;
if(strpos(strtolower(PHP_OS), 'win') === 0)
{
exit("start.php does not support windows, please use start_for_win.bat\n");
}
if(!extension_loaded('pcntl'))
{
exit("Error! <pcntl> extension not found! Please install pcntl extension.");
}
if(!extension_loaded('posix'))
{
exit("Error! <posix> extension not found! Please install posix extension.");
}
define('GLOBAL_START', 1);
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/start_worker1.php';
require_once __DIR__ . '/start_worker2.php';
// Run all services
Worker::runAll();
我想在worker2中我可以在评估函数$ws_worker->onWorkerStart
之前访问worker1对象,但我不知道如何实时访问worker1对象(我的意思是 - 访问对象的当前状态)。
我应该说,我是PHP OOP风格编程的新手。所以请告诉我我的错误在哪里。详细解释非常感谢。