那面以正在Yii框架高事例

一:swoole装备TCP

'swoole' => [
    // 日记文件路径
    'log_file' => '@console/log/swoole.log',
    // 铺排swoole_server错误日记挨印的品级,范畴是0-5。低于log_level配备的日记疑息没有会扔没
    'log_level' => 1,
    // 历程的PID存储文件
    'pid_file' => '@console/log/swoole.server.pid',

    // HTTP和谈设施
    'http' => [
        'host' => '0.0.0.0',
        'port' => '8889',

        // 同步工作的任务历程数目
        'task_worker_num' => 4,
    ],
    // TCP和谈部署
    'tcp' => [
        'host' => '0.0.0.0',
        'port' => '14000',

        // 同步事情的事情历程数目
        'task_worker_num' => 4,

        // 封用TCP-Keepalive逝世毗连检测
        'open_tcp_keepalive' => 1,
        // 单元秒,毗连正在n秒内不数据乞求,将入手下手对于此联接入止探测
        'tcp_keepidle' => 5 * 60,
        // 探测的次数,逾越次数后将close此毗连
        'tcp_keepcount' => 3,
        // 探测的隔绝距离功夫,单元秒
        'tcp_keepinterval' => 60,

        // 口跳检测,此选项暗示每一隔多暂轮循一次,单元为秒
        'heartbeat_check_interval' => 两 * 60,
        // 口跳检测,衔接最年夜容许余暇的光阴
        'heartbeat_idle_time' => 5 * 60,
    ]
],

2:swoole完成TCP处事基类

<必修php
/**
 * @link http://www.u-bo.com
 * @copyright 北京友专网络科技无限私司
 * @license http://www.u-bo.com/license/
 */

namespace console\swoole;

use Yii;
use yii\helpers\Console;
use yii\helpers\ArrayHelper;

/*
 * Swoole Server基类
 *
 * @author wangjian
 * @since 0.1
 */
abstract class BaseServer
{
    /**
     * @var Swoole\Server
     */
    public $swoole;
    /**
     * @var boolean DEBUG
     */
    public $debug = false;

    /**
     * __construct
     */
    public function __construct($httpConfig, $tcpConfig, $config = [])
    {
        $httpHost = ArrayHelper::remove($httpConfig, 'host');
        $httpPort = ArrayHelper::remove($httpConfig, 'port');
        $this->swoole = new \swoole_http_server($httpHost, $httpPort);
        $this->swoole->set(ArrayHelper::merge($config, $httpConfig));

        $this->swoole->on('start', [$this, 'onStart']);
        $this->swoole->on('request', [$this, 'onRequest']);
        $this->swoole->on('WorkerStart', [$this, 'onWorkerStart']);
        $this->swoole->on('WorkerStop', [$this, 'onWorkerStop']);
        $this->swoole->on('task', [$this, 'onTask']);
        $this->swoole->on('finish', [$this, 'onTaskFinish']);

        $this->swoole->on('shutdown', [$this, 'onShutdown']);

        $tcpHost = ArrayHelper::remove($tcpConfig, 'host');
        $tcpPort = ArrayHelper::remove($tcpConfig, 'port');
        $tcpServer = $this->swoole->listen($tcpHost, $tcpPort, SWOOLE_SOCK_TCP);
        $tcpServer->set($tcpConfig);
        $tcpServer->on('connect', [$this, 'onConnect']);
        $tcpServer->on('receive', [$this, 'onReceive']);
        $tcpServer->on('close', [$this, 'onClose']);
    }

    /*
     * 封动server
     */
    public function run()
    {
        $this->swoole->start();
    }

    /**
     * Server封动正在主历程的主线程时的归调变乱处置
     *
     * @param swoole_server $server
     */
    public function onStart(\swoole_server $server)
    {
        $startedAt = $this->beforeExec();

        $this->stdout("**Server Start**\n", Console::FG_GREEN);
        $this->stdout("master_pid: ");
        $this->stdout("{$server->master_pid}\n", Console::FG_BLUE);

        $this->onStartHandle($server);

        $this->afterExec($startedAt);
    }

    /**
     * 客户端取办事器创立毗连后的归调事故处置惩罚
     *
     * @param swoole_server $server
     * @param integer $fd
     * @param integer $reactorId
     */
    abstract public function onConnect(\swoole_server $server, int $fd, int $reactorId);

    /**
     * 当任事器支到来自客户真个数据时的归调事变处置
     *
     * @param swoole_server $server
     * @param integer $fd
     * @param integer $reactorId
     * @param string $data
     */
    abstract public function onReceive(\swoole_server $server, int $fd, int $reactorId, string $data);

    /**
     * 当做事器支到来自客户真个HTTP乞求时的归调事变措置
     *
     * @param swoole_http_request $request
     * @param swoole_http_response $response
     */
    abstract public function onRequest(\swoole_http_request $request, \swoole_http_response $response);

    /**
     * Worker历程/Task历程封动时领熟
     *
     * @param swoole_server $server
     * @param integer $worker_id
     */
    abstract public function onWorkerStart(\swoole_server $server, int $worker_id);

    /**
     * Worker历程/Task历程末行时领熟
     *
     * @param swoole_server $server
     * @param integer $worker_id
     */
    abstract public function onWorkerStop(\swoole_server $server, int $worker_id);

    /**
     * 同步工作处置惩罚
     *
     * @param swoole_server $server
     * @param integer $taskId
     * @param integer $srcWorkerId
     * @param mixed $data
     */
    abstract public function onTask(\swoole_server $server, int $taskId, int $srcWorkerId, mixed $data);

    /**
     * 同步工作措置实现
     *
     * @param swoole_server $server
     * @param integer $taskId
     * @param mixed $data
     */
    abstract public function onTaskFinish(\swoole_server $server, int $taskId, mixed $data);

    /**
     * 客户端取办事器断谢联接后的归调事变处置惩罚
     *
     * @param swoole_server $server
     * @param integer $fd
     */
    abstract public function onClose(\swoole_server $server, $fd);

    /**
     * Server畸形竣事时的归调事变处置
     *
     * @param swoole_server $server
     */
    public function onShutdown(\swoole_server $server)
    {
        $startedAt = $this->beforeExec();

        $this->stdout("**Server Stop**\n", Console::FG_GREEN);
        $this->stdout("master_pid: ");
        $this->stdout("{$server->master_pid}\n", Console::FG_BLUE);

        $this->onShutdownHandle($server);

        $this->afterExec($startedAt);
    }

    /**
     * Server封动正在主过程的主线程时的自界说变乱处置惩罚
     *
     * @param swoole_server $server
     */
    protected function onStartHandle(\swoole_server $server)
    {

    }

    /**
     * Server畸形停止时的自界说变乱措置
     *
     * @param swoole_server $server
     */
    protected function onShutdownHandle(\swoole_server $server)
    {

    }

    /**
     * 猎取乞求路由
     *
     * @param swoole_http_request $request
     */
    protected function getRoute(\swoole_http_request $request)
    {
        return ltrim($request->server['request_uri'], '/');
    }

    /**
     * 猎取乞求的GET参数
     *
     * @param swoole_http_request $request
     */
    protected function getParams(\swoole_http_request $request)
    {
        return $request->get;
    }

    /**
     * 解析支到的数据
     *
     * @param string $data
     */
    protected function decodeData($data)
    {
        return json_decode($data, true);
    }

    /**
     * Before Exec
     */
    protected function beforeExec()
    {
        $startedAt = microtime(true);
        $this->stdout(date('Y-m-d H:i:s') . "\n", Console::FG_YELLOW);
        return $startedAt;
    }

    /**
     * After Exec
     */
    protected function afterExec($startedAt)
    {
        $duration = number_format(round(microtime(true) - $startedAt, 3), 3);
        $this->stdout("{$duration} s\n\n", Console::FG_YELLOW);
    }

    /**
     * Prints a string to STDOUT.
     */
    protected function stdout($string)
    {
        if (Console::streamSupportsAnsiColors(\STDOUT)) {
            $args = func_get_args();
            array_shift($args);
            $string = Console::ansiFormat($string, $args);
        }
        return Console::stdout($string);
    }
}

三:swoole把持类(承继swoole基类)

<必修php
/**
 * @link http://www.u-bo.com
 * @copyright 北京友专网络科技无穷私司
 * @license http://www.u-bo.com/license/
 */

namespace console\swoole;

use Yii;
use yii\db\Query;
use yii\helpers\Console;
use yii\helpers\VarDumper;
use apps\sqjc\models\WaterLevel;
use apps\sqjc\models\WaterLevelLog;
use co妹妹on\models\Bayonet;
use co妹妹on\models\Device;
use co妹妹on\models\DeviceCategory;

/**
 * Swoole Server测试类
 *
 * @author wangjian
 * @since 1.0
 */
class Server extends BaseServer
{
    /**
     * @inheritdoc
     */
    public function onConnect($server, $fd, $reactorId)
    {
        $startedAt = $this->beforeExec();

        $this->stdout("**Connection Open**\n", Console::FG_GREEN);
        $this->stdout("fd: ");
        $this->stdout("{$fd}\n", Console::FG_BLUE);

        $this->afterExec($startedAt);
    }

    /**
     * @inheritdoc
     */
    public function onReceive($server, $fd, $reactorId, $data)
    {
        $startedAt = $this->beforeExec();

        $this->stdout("**Received Message**\n", Console::FG_GREEN);

        $this->stdout("fd: ");
        $this->stdout("{$fd}\n", Console::FG_BLUE);

        $this->stdout("data: ");//接受的数据
        $this->stdout("{$data}\n", Console::FG_BLUE);



        $result = $server->send($fd, '答复动静');



        $this->afterExec($startedAt);
    }


    /**
     * @inheritdoc
     */
    public function onRequest($request, $response)
    {
        $startedAt = $this->beforeExec();

        $this->stdout("**HTTP Request**\n", Console::FG_GREEN);

        $this->stdout("fd: ");
        $this->stdout("{$request->fd}\n", Console::FG_BLUE);

        $response->status(两00);
        $response->end('success');

        $this->afterExec($startedAt);
    }

    /**
     * @inheritdoc
     */
    public function onClose($server, $fd)
    {
        $startedAt = $this->beforeExec();

        $this->stdout("**Connection Close**\n", Console::FG_GREEN);

        $this->stdout("fd: ");
        $this->stdout("{$fd}\n", Console::FG_BLUE);

        $this->afterExec($startedAt);
    }



    /**
     * @inheritdoc
     */
    public function onTask($server, $taskId, $srcWorkerId, $data)
    {
        $startedAt = $this->beforeExec();

        $this->stdout("New AsyncTask: ");
        $this->stdout("{$taskId}\n", Console::FG_BLUE);
        $this->stdout("{$data}\n", Console::FG_BLUE);

        $server->finish($data);

        $this->afterExec($startedAt);
    }

    /**
     * @inheritdoc
     */
    public function onWorkerStop($server, $worker_id)
    {
        // Yii::$app->db->close();
    }
    /**
     * @inheritdoc
     */
    public function onWorkerStart($server, $worker_id)
    {
        // Yii::$app->db->open();
    }


    /**
     * @inheritdoc
     */
    public function onTaskFinish($server, $taskId, $data)
    {
        $startedAt = $this->beforeExec();

        $this->stdout("AsyncTask finished: ");
        $this->stdout("{$taskId}\n", Console::FG_BLUE);

        $this->afterExec($startedAt);
    }
}

四:把持TCP办事

<必修php
/**
 * @link http://www.u-bo.com
 * @copyright 北京友专网络科技无穷私司
 * @license http://www.u-bo.com/license/
 */

namespace console\controllers;

use Yii;
use yii\helpers\Console;
use yii\helpers\FileHelper;
use yii\helpers\ArrayHelper;
use console\swoole\Server;

/**
 * WebSocket Server controller.
 *
 * @see https://github.com/tystudy/yii两-swoole-websocket/blob/master/README.md
 *
 * @author wangjian
 * @since 1.0
 */
class SwooleController extends Controller
{
    /**
     * @var string 监听IP
     */
    public $host;
    /**
     * @var string 监听端心
     */
    public $port;
    /**
     * @var boolean 可否以守御历程体式格局封动
     */
    public $daemon = false;
    /**
     * @var boolean 能否封动测试类
     */
    public $test = false;

    /**
     * @var array Swoole参数铺排项
     */
    private $_params;

    /**
     * @var array Swoole参数配备项(HTTP和谈)
     */
    private $_http_params;
    /**
     * @var array Swoole参数设施项(TCP和谈)
     */
    private $_tcp_params;

    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            //断定可否封闭swoole拓铺
            if (!extension_loaded('swoole')) {
                return false;
            }

            //猎取swoole配备疑息
            if (!isset(Yii::$app->params['swoole'])) {
                return false;
            }
            $this->_params = Yii::$app->params['swoole'];
            $this->_http_params = ArrayHelper::remove($this->_params, 'http');
            $this->_tcp_params = ArrayHelper::remove($this->_params, 'tcp');

            foreach ($this->_params as &$param) {
                if (strncmp($param, '@', 1) === 0) {
                    $param = Yii::getAlias($param);
                }
            }

            $this->_params = ArrayHelper::merge($this->_params, [
                'daemonize' => $this->daemon
            ]);

            return true;
        } else {
            return false;
        }
    }
    /**
     * 封动管事
     */
    public function actionStart()
    {
        if ($this->getPid() !== false) {
            $this->stdout("WebSocket Server is already started!\n", Console::FG_RED);
            return self::EXIT_CODE_NORMAL;
        }
        $server = new Server($this->_http_params, $this->_tcp_params, $this->_params);
        $server->run();
    }

    /**
     * 完毕任事
     */
    public function actionStop()
    {
        $pid = $this->getPid();
        if ($pid === false) {
            $this->stdout("Tcp Server is already stoped!\n", Console::FG_RED);
            return self::EXIT_CODE_NORMAL;
        }

        \swoole_process::kill($pid);
    }

    /**
     * 清算日记文件
     */
    public function actionClearLog()
    {
        $logFile = Yii::getAlias($this->_params['log_file']);
        FileHelper::unlink($logFile);
    }

    /**
     * 猎取历程PID
     *
     * @return false|integer PID
     */
    private function getPid()
    {
        $pidFile = $this->_params['pid_file'];
        if (!file_exists($pidFile)) {
            return false;
        }

        $pid = file_get_contents($pidFile);
        if (empty($pid)) {
            return false;
        }

        $pid = intval($pid);
        if (\swoole_process::kill($pid, 0)) {
            return $pid;
        } else {
            FileHelper::unlink($pidFile);
            return false;
        }
    }

    /**
     * @inheritdoc
     */
    public function options($actionID)
    {
        return ArrayHelper::merge(parent::options($actionID), [
            'daemon',
            'test'
        ]);
    }

    /**
     * @inheritdoc
     */
    public function optionAliases()
    {
        return ArrayHelper::merge(parent::optionAliases(), [
            'd' => 'daemon',
            't' => 'test',
        ]);
    }
}

以上即是php应用swoole完成TCP办事的具体形式,更多闭于php swoole完成TCP管事的质料请存眷剧本之野其余相闭文章!

点赞(50) 打赏

评论列表 共有 0 条评论

暂无评论

微信小程序

微信扫一扫体验

立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部