swoole客户端

文章目录

1.swoole客户端能解决什么样的问题?

2.如何应用?

3.注意事项

1.首先明确swoole客户端能帮忙咱们解决什么样的问题?

业务场景当业务中须要链接TCP,UDP,socket,websocket 服务时,咱们须要编写一个客户端去链接对应的服务(比方链接某些数据源)。
此时有很多种的抉择,workerman的AsyncTcpConnection,或者应用php自带的socket函数(socket_create,socket_read等函数),swoole的客户端(Swoole\Client)等都能够。各有优劣,抉择适宜本人和业务的就好,这次咱们抉择Swoole\Client。

2.如何应用?
废话不多说,间接上我封装好的代码,看不懂多看正文了解,能够珍藏不便当前能够间接应用。

class SwooleClient{    //链接对象    private $client;    /**     * SwooleClient constructor.     */    public function __construct()    {        $this->client = new Swoole\Client(SWOOLE_SOCK_TCP);        $this->client->set(array(            'open_eof_check' => true,   //关上EOF检测            'package_eof'    => "\r\n", //设置EOF,包之间的分隔符            'package_max_length' => 1024 * 1024 * 2,//设置一个包的最大数据包尺寸,单位为字节。默认2m        ));    }    /**     * Notes: 链接对应的ip     * User: 闻铃     * DateTime: 2021/11/17 下午10:46     * @param string $ip 链接的ip,本地或外网ip     * @param  int $port 端口号     * @throws \Exception     */    public function connect($ip = '127.0.0.1', $port = 9501)    {        if (!$this->client->connect($ip, $port, -1)) {            throw new \Exception(sprintf('Swoole Error: %s', $this->client->errCode));        }    }    /**     * Notes: 发送数据     * User: 闻铃     * DateTime: 2021/11/17 下午10:44     * @param $data 发送的数据     * @return mixed     * @throws \Exception     */    public function send($data)    {        if ($this->client->isConnected()) {            if (!is_string($data)) {                $data = json_encode($data);            }            return $this->client->send($data);        } else {            throw new \Exception('Swoole Server does not connected.');        }    }    /**     * Notes: 敞开链接     * User: 闻铃     * DateTime: 2021/11/17 下午10:45     */    public function close()    {        $this->client->close();    }    /**     * Notes: 接收数据     * User: 闻铃     * DateTime: 2021/11/17 下午10:45     * @return array     */    public function recv()    {        //承受数据        return $this->client->recv();    }}

如果想要作为webscoket客户端的话,也是能够的,能够应用官网的websocket包(saber)
后续更新

3.注意事项
。。。后续更新