【发布时间】:2020-05-05 16:58:02
【问题描述】:
我的问题是我不知道如何在不需要与客户端交互的情况下检查某些内容。我想每分钟检查一次怪物重生的时间(通过从数据库中获取数据),如果是 - 我想向客户发送一些消息。我可以向客户发送一些东西,但是如何每分钟执行特定的代码?目前我的服务器端是这样的:
<?php
set_time_limit(0);
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
use Ratchet\Server\IoServer;
use Ratchet\Http\HttpServer;
use Ratchet\WebSocket\WsServer;
require_once '../vendor/autoload.php';
class Chat implements MessageComponentInterface {
protected $clients;
protected $users;
public function __construct() {
$this->clients = new \SplObjectStorage;
}
public function onOpen(ConnectionInterface $conn) {
$this->clients->attach($conn);
$this->users[$conn->resourceId] = $conn;
}
public function onClose(ConnectionInterface $conn) {
$this->clients->detach($conn);
unset($this->users[$conn->resourceId]);
}
public function onMessage(ConnectionInterface $from, $data) {
$from_id = $from->resourceId;
$data = json_decode($data);
$type = $data->type;
switch ($type) {
case 'test':
$user_id = $data->user_id;
$chat_msg = $data->chat_msg;
$response_from = "<span style='color:#999'><b>".$user_id.":</b> ".$chat_msg."</span><br><br>";
$response_to = "<b>".$user_id."</b>: ".$chat_msg."<br><br>";
// Output
$from->send(json_encode(array("type"=>$type,"msg"=>$response_from)));
foreach($this->clients as $client)
{
if($from!=$client)
{
$client->send(json_encode(array("type"=>$type,"msg"=>$response_to)));
}
}
break;
case 'chat':
$user_id = $data->user_id;
$chat_msg = $data->chat_msg;
$response_from = "<span style='color:#999'><b>".$user_id.":</b> ".$chat_msg."</span><br><br>";
$response_to = "<b>".$user_id."</b>: ".$chat_msg."<br><br>";
// Output
$from->send(json_encode(array("type"=>$type,"msg"=>$response_from)));
foreach($this->clients as $client)
{
if($from!=$client)
{
$client->send(json_encode(array("type"=>$type,"msg"=>$response_to)));
}
}
break;
}
}
public function onError(ConnectionInterface $conn, \Exception $e) {
$conn->close();
}
}
$server = IoServer::factory(
new HttpServer(new WsServer(new Chat())),
8080
);
$server->run();
?>
【问题讨论】:
-
如果你使用像 laravel 这样的框架,你可以有像
$schedule->command('spawn:monster')->everyMinute()这样的 Cron 作业。您可以在Http/Console目录中拥有您的spawn:monster逻辑。
标签: php websocket ratchet phpwebsocket