KTV/app/Services/TcpSocketClient.php
allen.yan ae5ed4aa1f Swagger 都改到ApiResponse 輸出
Swagger Room加入TcpSocketClient
Swagger room 加入 設備註冊,設備開關
Swagger room 有異動需要寫記錄
20250519
2025-05-19 16:08:35 +08:00

43 lines
1.1 KiB
PHP

<?php
namespace App\Services;
class TcpSocketClient
{
protected $ip;
protected $port;
protected $timeout;
public function __construct(string $ip, int $port, int $timeout = 5)
{
$this->ip = $ip;
$this->port = $port;
$this->timeout = $timeout;
}
public function send(string $data): string
{
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
throw new \Exception("Socket create failed: " . socket_strerror(socket_last_error()));
}
$result = socket_connect($socket, $this->ip, $this->port);
if ($result === false) {
throw new \Exception("Socket connect failed: " . socket_strerror(socket_last_error($socket)));
}
socket_write($socket, $data, strlen($data));
$response = '';
while ($out = socket_read($socket, 2048)) {
$response .= $out;
// 根據協議判斷是否結束接收,可以自行調整
if (strpos($response, "\n") !== false) {
break;
}
}
socket_close($socket);
return $response;
}
}