This commit is contained in:
gaofeng
2026-06-17 09:23:18 +08:00
commit 81ade70944
1638 changed files with 213697 additions and 0 deletions

View File

@@ -0,0 +1,63 @@
<?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;
}
}