SwooleClient.php 1.4 KB
<?php
/**
 * Created by PhpStorm.
 * User: luoys
 * Date: 2019/2/13
 * Time: 11:42
 */

class SwooleClient
{
    private $_client;

    public function __construct($type = SWOOLE_SOCK_TCP, $is_sync = SWOOLE_SOCK_SYNC)
    {
        $this->_client = new swoole_client($type, $is_sync);
    }

    public function connect($host, $port = null, $timeout = null, $sock_flag = null)
    {
        if (!$this->_client->connect($host, $port, $timeout, $sock_flag)) {
            exit("connect failed. Error: {$this->_client->errCode}\n");
        }
    }

    public function send($data)
    {
        if ($this->_client->send($data) === false)
        {
            exit("send data failed. Error: {$this->_client->errCode} \n");
        }
    }

    public function sendfile($filename, $offset, $length)
    {
        if ($this->_client->sendfile($filename, $offset, $length) === false) {
            exit("{$filename} is not exist. \n");
        }
    }

    public function sendto($ip, $port, $data)
    {
        $this->_client->sendto($ip, $port, $data);
    }

    public function recv($size = 65535, $flags = 0)
    {
        if (($recv = $this->_client->recv($size, $flags)) === false) {
            exit("receive data failed. Error: {$this->_client->errCode} \n");
        }
        return $recv;
    }

}

$client = new SwooleClient();
$client->connect('127.0.0.1', 9501);
$client->send('11223');

$recv = $client->recv();
echo $recv;