Swoole 学习笔记

简介

Swoole是PHP语言的高性能网络通信框架,提供了PHP语言的异步多线程服务器,异步TCP/UDP网络客户端,异步MySQL,数据库连接池,AsyncTask,消息队列,毫秒定时器,异步文件读写,异步DNS查询。

安装Swoole

 

服务端实例代码(阻塞)

<?php


class Server
{
    private $serv;

    public function __construct()
    {
        $this->serv = new swoole_server("0.0.0.0", 9501);
        $this->serv->set(array(
            'worker_num' => 8,  //每个worker大概40M内存 cpu1~4倍最合理
            'daemonize' => false,  //是否守护进程后台执行
//            'log_file' => '/data/log/swoole.log',  //结果日志,守护运行时配置
            'debug_mode' => 1,
            'max_request' => 10000,  //设置worker进程的最大任务数
            'dispatch_mode' => 2,  //轮循模式,收到会轮循分配给每一个worker进程
            'task_worker_num' => 8,  //配置task进程的数量
            'task_max_request' => 10000  //设置task进程的最大任务数

        ));
        $this->serv->on('Start', array($this, 'onStart'));
        $this->serv->on('Connect', array($this, 'onConnect'));
        $this->serv->on('Receive', array($this, 'onReceive'));
        $this->serv->on('Close', array($this, 'onClose'));
        // bind callback
        $this->serv->on('Task', array($this, 'onTask'));
        $this->serv->on('Finish', array($this, 'onFinish'));
        $this->serv->start();
    }


    public function onStart($serv)
    {
        echo "Start\n";
    }

    public function onConnect($serv, $fd, $from_id)
    {
        echo "Client {$fd} connect\n";
    }

    public function onReceive(swoole_server $serv, $fd, $from_id, $data)
    {
        echo "Get Message From Client {$fd}:{$data}\n";
        // send a task to task worker.
        $param = array(
            'fd' => $fd
        );

        //调用task
        $serv->task(json_encode($param));


    }

    public function onClose($serv, $fd, $from_id)
    {
        echo "Client {$fd} close connection\n";
    }

    public function onTask($serv, $task_id, $from_id, $data)
    {

        echo "This Task {$task_id} from Worker {$from_id}\n";
        echo "Data: {$data}\n";
        for ($i = 0; $i < 10; $i++) {
            sleep(1);
            echo "Taks {$task_id} Handle {$i} times...\n";
        }
        $fd = json_decode($data, true)['fd'];
        $serv->send($fd, "Data in Task {$task_id}");
        return "Task {$task_id}'s result";
    }

    public function onFinish($serv, $task_id, $data)
    {
        echo "Task {$task_id} finish\n";
        echo "Result: {$data}\n";
    }
}

$server = new Server();

其中 $fd 为客户端链接id ,$from_id为 Worker产生的id  ,$task_id 为task id

客户端实例代码(阻塞式)

<?php

$client = new swoole_client(SWOOLE_SOCK_TCP);
if (!$client->connect('127.0.0.1', 9501, -1)) {
    exit("connect failed. Error: {$client->errCode}\n");
}
$client->send("hello world\n");
echo $client->recv();
$client->close();

 

使用注意

ulimit -n 要调整为100000甚至更大

# ulimit -n 1000000

 

 

参考资料

发表评论

电子邮件地址不会被公开。 必填项已用*标注