[英]How to check something every 1 minute, and then send it to client?
我的问题是我不知道如何在不需要与客户端交互的情况下检查某些内容。 我想每分钟检查一次怪物重生的时间(通过从数据库中获取数据),如果是 - 我想向客户发送一些消息。 我可以向客户发送一些东西,但是如何每分钟执行特定的代码? 目前我的服务器端如下所示:
<?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 代码。
您需要与客户端建立开放连接,才能向他们发送任何数据。 有两种方法可以做到:
来自客户端的每分钟请求数据,如果有 1000 个客户端,则每分钟将收到 1000 个请求
使用 websocket。 例如使用库https://socket.io/ ,非常简单易上手。 缺点你需要在 nodejs 上编写这部分网站。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.