我的问题是,我不知道如何在不需要与客户端交互的情况下检查一些东西,我想每分钟检查一下怪物是否到了重生的时间(从数据库中获取数据),如果是的话,我想给客户端发送一些msg。我想每分钟检查一次怪物是否到了重生的时间(通过从数据库中获取数据),如果是的话,我想发送一些msg给客户端。我可以发送一些东西到客户端,但是如何每分钟执行特定的代码?目前我的服务器端是这样的。
<?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();
?>
一个解决方案。
写一个unix cron脚本或者windows的计划任务,每分钟运行一次php代码。
你需要和客户有一个开放的连接,以便向他们发送任何数据。有两种方法可以做到这一点。
每分钟从客户端请求数据, const- 1000个客户端, 你每分钟会有1000个请求.
使用websocket。例如,使用库 https:/socket.io。,非常简单,容易上手。缺点你需要在nodejs上写这部分网站。