|
...
|
...
|
@@ -8,30 +8,44 @@ |
|
|
|
*/
|
|
|
|
|
|
|
|
namespace App\Helper;
|
|
|
|
|
|
|
|
require __DIR__ . '/vendor/autoload.php';
|
|
|
|
use WebSocket\Client;
|
|
|
|
class Socket
|
|
|
|
{
|
|
|
|
public function socket($data){
|
|
|
|
// Socket 服务器的 IP 和端口
|
|
|
|
$socketServerIp = '127.0.0.1';
|
|
|
|
$socketServerPort = 9555; // 替换为实际端口
|
|
|
|
// 创建一个 TCP Socket 客户端
|
|
|
|
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
|
|
|
|
if ($socket === false) {
|
|
|
|
return response()->json(['error' => 'Socket creation failed']);
|
|
|
|
private $client;
|
|
|
|
|
|
|
|
public $serverIp = '127.0.0.1';
|
|
|
|
|
|
|
|
public $serverPort = '9555';
|
|
|
|
|
|
|
|
public function __construct() {
|
|
|
|
$socketUrl = "ws://{$this->serverIp}:{$this->serverPort}";
|
|
|
|
$this->client = new Client($socketUrl);
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @remark :发送消息
|
|
|
|
* @name :send
|
|
|
|
* @author :lyh
|
|
|
|
* @method :post
|
|
|
|
* @time :2023/8/31 10:18
|
|
|
|
*/
|
|
|
|
public function send($data) {
|
|
|
|
$this->client->send($data);
|
|
|
|
}
|
|
|
|
// 连接到 Socket 服务器
|
|
|
|
$result = socket_connect($socket, $socketServerIp, $socketServerPort);
|
|
|
|
if ($result === false) {
|
|
|
|
return response()->json(['error' => 'Socket connection failed']);
|
|
|
|
|
|
|
|
public function receive() {
|
|
|
|
return $this->client->receive();
|
|
|
|
}
|
|
|
|
$data = 'hello';
|
|
|
|
// 发送数据到 Socket 服务器
|
|
|
|
socket_write($socket, $data, strlen($data));
|
|
|
|
// 从服务器接收数据
|
|
|
|
$response = socket_read($socket, 1024);
|
|
|
|
// 关闭 Socket 连接
|
|
|
|
socket_close($socket);
|
|
|
|
return response()->json(['response' => $response]);
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @remark :关闭连接
|
|
|
|
* @name :close
|
|
|
|
* @author :lyh
|
|
|
|
* @method :post
|
|
|
|
* @time :2023/8/31 10:21
|
|
|
|
*/
|
|
|
|
public function close() {
|
|
|
|
$this->client->close();
|
|
|
|
}
|
|
|
|
} |
...
|
...
|
|