swoole TCP客户端

<?php
class TcpClient
{
    const HOST = '127.0.0.1';
    const PROT = '9501';
    public $client = null;  // 存放tcp连接信息

    public function __construct()
    {
        $this->client = new swoole\Client(SWOOLE_SOCK_TCP);

        if (!$this->client->connect(self::HOST, self::PROT)) {
            echo '连接失败';die;
        }

        $this->sendMsg();
        $this->receiveData();
    }

    /**
     * 接收客户输入的消息 并发送给TCP服务端
     */
    public function sendMsg()
    {
        // php cli常量
        fwrite(STDOUT, '请输入消息:');
        $msg = trim(fgets(STDIN));

        // 发送信息给 TCP服务器
        $this->client->send($msg);
    }

    /**
     * 接收服务端返回的数据
     */
    public function receiveData()
    {
        $result = $this->client->recv();
        echo $result. PHP_EOL;
    }
}
new TcpClient();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在ThinkPHP6中,如果你已经建立了Swoole TCP客户端的长连接,你可以在后续的请求中重复使用该连接进行通信。下面是一个简单的示例: 假设你已经建立了一个长连接并保存在某个全局变量中,可以在需要发送请求的地方使用该连接进行通信。 ```php <?php namespace app\controller; use Swoole\Coroutine\Client; class TcpClient { private $client; // 保存TCP客户端连接的变量 public function index() { // 首次发送请求,建立长连接 if (!$this->client) { $this->client = new Client(SWOOLE_SOCK_TCP); // 连接到服务器 if (!$this->client->connect('127.0.0.1', 9501, 0.5)) { return '连接服务器失败'; } } // 发送数据 $this->client->send('Hello, Server!'); // 接收服务器返回的数据 $response = $this->client->recv(); if ($response === false) { return '接收数据失败'; } // 发送第二个请求 $this->client->send('Hello again, Server!'); // 接收服务器返回的数据 $response2 = $this->client->recv(); if ($response2 === false) { return '接收数据失败'; } return [$response, $response2]; } public function __destruct() { // 在控制器销毁时关闭连接 if ($this->client) { $this->client->close(); } } } ``` 在上述示例中,我们在`index`方法中首次发送请求时建立了长连接,并将连接保存在`$this->client`变量中。然后,我们可以重复使用该连接发送请求并接收响应。在控制器销毁时,我们通过`__destruct`方法关闭连接。 请根据你的实际需求进行相应的修改和补充,确保长连接的正确使用和关闭。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值