php artisan make:command Haha
<?php
namespace App\Console\Commands;
use App\Sockets\SmartCare\WristMixTcpClient;
use Illuminate\Console\Command;
class Haha extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'haha';
/**
* The console command description.
*
* @var string
*/
protected $description = 'test';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return void
*/
public function handle()
{
$mix_tcp = new WristMixTcpClient();//这个类文件将在下文贴出,你可以把这个文件放在任意目录,也可以取任意文件名,在头部引入即可.
$mix_tcp->runClient();
}
}
<?php
namespace App\Sockets\SmartCare;
use App\Http\Controllers\Controller;
use Swoole\Coroutine\Client;
use function Swoole\Coroutine\run;
class WristMixTcpClient extends Controller
{
public function runClient()
{
run(function () {
$client = new Client(SWOOLE_SOCK_TCP);
$client->set(array(
'open_eof_split' => true,
'package_eof' => "\r\n",
));
if (!$client->connect('127.0.0.1', 1111, 0.5)) {
echo "connect failed. Error: {$client->errCode}\n";
}
$client->send("hello world\n");
while (true) {
$data = $client->recv();
if (strlen($data) > 0) {
// dump(strlen($data));
// dump($data);
dump(json_decode($data, true));
//业务逻辑写在这
// $client->send(time() . PHP_EOL);
} else {
if ($data === '') {
// 全等于空 直接关闭连接
$client->close();
break;
} else {
if ($data === false) {
// 可以自行根据业务逻辑和错误码进行处理,例如:
// 如果超时时则不关闭连接,其他情况直接关闭连接
if ($client->errCode !== SOCKET_ETIMEDOUT) {
$client->close();
break;
}
} else {
$client->close();
break;
}
}
}
\Co::sleep(1);
}
});
}
}
php artisan haha