Files
miniapi/app/service/SwooleService.php
gaofeng 81ade70944 提交
2026-06-17 09:23:18 +08:00

63 lines
1.7 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace app\service;
use Swoole\Client;
class SwooleService
{
private static ?self $instance = null;
private string $host = 'ossup.jzvisa.com';
private int $port = 19501;
private float $timeout = 3.0;
// 私有化构造函数,保留原来的单例调用方式
private function __construct()
{
}
// 获取单例
public static function getInstance(): self
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
// 发送任务:短连接模式,每次连接、发送、关闭
public function sendTask(array $task): bool
{
$client = new Client(SWOOLE_SOCK_TCP);
try {
if (!$client->connect($this->host, $this->port, $this->timeout)) {
throw new \RuntimeException(
"Cannot connect to Swoole Server {$this->host}:{$this->port}, error: {$client->errCode}"
);
}
$data = json_encode($task, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if ($data === false) {
throw new \RuntimeException('JSON encode failed: ' . json_last_error_msg());
}
// 你的服务端使用 \r\n 作为 package_eof所以这里必须加 \r\n
$sendResult = $client->send($data . "\r\n");
return $sendResult !== false;
} finally {
if ($client->isConnected()) {
$client->close();
}
}
}
// 保留 close 方法,避免旧代码调用时报错
public function close(): void
{
self::$instance = null;
}
}