连续复制
一键复制
一键打包

client

tcp_client.php

<?php
// 连接 swoole tcp 服务
$client = new swoole_client(SWOOLE_SOCK_TCP);
if(!$client->connect("127.0.0.1", 9501)) {
    echo "连接失败";
    exit;
}
/// php cli常量
fwrite(STDOUT, "请输入消息:");
$msg = trim(fgets(STDIN));
// 发送消息给 tcp server服务器
$client->send($msg);
// 接受来自server 的数据
$result = $client->recv();
echo $result;

coroutine

redis.php

<?php
$http = new swoole_http_server('0.0.0.0', 8001);
$http->on('request', function($request, $response) {
    // 获取redis 里面 的key的内容, 然后输出浏览器
    $redis = new Swoole\Coroutine\Redis();
    $redis->connect('127.0.0.1', 6379);
    $value = $redis->get($request->get['a']);
    $response->header("Content-Type", "text/plain");
    $response->end($value);
});
$http->start();

io

1.log

20180306 18:08:4320180306 18:10:0720180306 18:10:0920180306 18:10:0920180306 18:10:39
20180306 18:10:40

1.txt

test-io

mysql.php

<?php
class AysMysql {
    /**
     * @var string
     */
    public $dbSource = "";
    /**
     * mysql的配置
     * @var array
     */
    public $dbConfig = [];
    public function __construct() {
        //new swoole_mysql;
        $this->dbSource = new Swoole\Mysql;
        $this->dbConfig = [
            'host' => '127.0.0.1',
            'port' => 5123,
            'user' => 'root',
            'password' => 123456,
            'database' => 'swoole',
            'charset' => 'utf8',
        ];
    }
    public function update() {
    }
    public function add() {
    }
    /**
     * mysql 执行逻辑
     * @param $id
     * @param $username
     * @return bool
     */
    public function execute($id, $username) {
        // connect
        $this->dbSource->connect($this->dbConfig, function($db, $result) use($id, $username)  {
            echo "mysql-connect".PHP_EOL;
            if($result === false) {
                var_dump($db->connect_error);
                // todo
            }
            //$sql = "select * from test where id=1";
            $sql = "update test set `username` = '".$username."' where id=".$id;
            // insert into
            // query (add select update delete)
            $db->query($sql, function($db, $result){
                // select => result返回的是 查询的结果内容
                if($result === false) {
                    // todo
                    var_dump($db->error);
                }elseif($result === true) {// add update delete
                    // todo
                    var_dump($db->affected_rows);
                }else {
                    print_r($result);
                }
                $db->close();
            });
        });
        return true;
    }
}
$obj = new AysMysql();
$flag = $obj->execute(1, 'singwa-111112');
var_dump($flag).PHP_EOL;
echo "start".PHP_EOL;
for($i=0; $i<900000;$i++) {
    echo $i.PHP_EOL;
}
// 详情页 -》mysql(阅读数) -》msyql 文章 +1 -》页面数据呈现出来

read.php

<?php
/**
 * 读取文件
 * __DIR__
 */
$result = Swoole\Async::readfile(__DIR__."/1.txt", function($filename, $fileContent) {
    echo "filename:".$filename.PHP_EOL;  // \n \r\n
    echo "content:".$fileContent.PHP_EOL;
});
var_dump($result);
echo "start".PHP_EOL;

redis.php

<?php
$redisClient = new swoole_redis;// Swoole\Redis
$redisClient->connect('127.0.0.1', 6379, function(swoole_redis $redisClient, $result) {
    echo "connect".PHP_EOL;
    var_dump($result);
    // 同步 redis (new Redis())->set('key',2);
    /*$redisClient->set('singwa_1', time(), function(swoole_redis $redisClient, $result) {
        var_dump($result);
    });*/
    /*$redisClient->get('singwa_1', function(swoole_redis $redisClient, $result) {
        var_dump($result);
        $redisClient->close();
    });*/
    $redisClient->keys('*gw*', function(swoole_redis $redisClient, $result) {
        var_dump($result);
        $redisClient->close();
    });
});
echo "start".PHP_EOL;

write.php

<?php
$content = date("Ymd H:i:s").PHP_EOL;
swoole_async_writefile(__DIR__."/1.log", $content, function($filename){
    // todo
    echo "success".PHP_EOL;
}, FILE_APPEND);
// file_put_contents();
echo "start".PHP_EOL;

memory

table.php

<?php
// 创建内存表
$table = new swoole_table(1024);
// 内存表增加一列
$table->column('id', $table::TYPE_INT, 4);
$table->column('name', $table::TYPE_STRING, 64);
$table->column('age', $table::TYPE_INT, 3);
$table->create();
$table->set('singwa_imooc', ['id' => 1, 'name'=> 'singwa', 'age' => 30]);
// 另外一种方案
$table['singwa_imooc_2'] = [
    'id' => 2,
    'name' => 'singwa2',
    'age' => 31,
];
$table->decr('singwa_imooc_2', 'age', 2);
print_r($table['singwa_imooc_2']);
echo "delete start:".PHP_EOL;
$table->del('singwa_imooc_2');
print_r($table['singwa_imooc_2']);

process

curl.php

<?php
echo "process-start-time:".date("Ymd H:i:s");
$workers = [];
$urls = [
    'http://baidu.com',
    'http://sina.com.cn',
    'http://qq.com',
    'http://baidu.com?search=singwa',
    'http://baidu.com?search=singwa2',
    'http://baidu.com?search=imooc',
];
for($i = 0; $i < 6; $i++) {
    // 子进程
    $process = new swoole_process(function(swoole_process $worker) use($i, $urls) {
        // curl
        $content = curlData($urls[$i]);
        //echo $content.PHP_EOL;
        $worker->write($content.PHP_EOL);
    }, true);
    $pid = $process->start();
    $workers[$pid] = $process;
}
foreach($workers as $process) {
    echo $process->read();
}
/**
 * 模拟请求URL的内容  1s
 * @param $url
 * @return string
 */
function curlData($url) {
    // curl file_get_contents
    sleep(1);
    return $url . "success".PHP_EOL;
}
echo "process-end-time:".date("Ymd H:i:s");

process.php

<?php
$process = new swoole_process(function(swoole_process $pro) {
    // todo
    // php redis.php
    $pro->exec("/home/work/study/soft/php/bin/php", [__DIR__.'/../server/http_server.php']);
}, false);
$pid = $process->start();
echo $pid . PHP_EOL;
swoole_process::wait();

server

access.log

http_server.php

<?php
$http = new swoole_http_server("0.0.0.0", 8811);
$http->set(
    [
        'enable_static_handler' => true,
        'document_root' => "/home/work/hdtocs/swoole_mooc/data",
    ]
);
$http->on('request', function($request, $response) {
    //print_r($request->get);
    $content = [
        'date:' => date("Ymd H:i:s"),
        'get:' => $request->get,
        'post:' => $request->post,
        'header:' => $request->header,
    ];
    swoole_async_writefile(__DIR__."/access.log", json_encode($content).PHP_EOL, function($filename){
        // todo
    }, FILE_APPEND);
    $response->cookie("singwa", "xsssss", time() + 1800);
    $response->end("sss". json_encode($request->get));
});
$http->start();

tcp.php

<?php
//创建Server对象,监听 127.0.0.1:9501端口
$serv = new swoole_server("127.0.0.1", 9501);
$serv->set([
    'worker_num' => 6 , // worker进程数 cpu 1-4
    'max_request' => 10000,
]);
//监听连接进入事件
/**
 * $fd 客户端连接的唯一标示
 * $reactor_id 线程id
 */
$serv->on('connect', function ($serv, $fd, $reactor_id) {
    echo "Client: {$reactor_id} - {$fd}-Connect.\n";
});
//监听数据接收事件
$serv->on('receive', function ($serv, $fd, $reactor_id, $data) {
    $serv->send($fd, "Server: {$reactor_id} - {$fd}".$data);
});
//监听连接关闭事件
$serv->on('close', function ($serv, $fd) {
    echo "Client: Close.\n";
});
//启动服务器
$serv->start();

ws.php

<?php
class Ws {
    CONST HOST = "0.0.0.0";
    CONST PORT = 8812;
    public $ws = null;
    public function __construct() {
        $this->ws = new swoole_websocket_server("0.0.0.0", 8812);
        $this->ws->set(
            [
                'worker_num' => 2,
                'task_worker_num' => 2,
            ]
        );
        $this->ws->on("open", [$this, 'onOpen']);
        $this->ws->on("message", [$this, 'onMessage']);
        $this->ws->on("task", [$this, 'onTask']);
        $this->ws->on("finish", [$this, 'onFinish']);
        $this->ws->on("close", [$this, 'onClose']);
        $this->ws->start();
    }
    /**
     * 监听ws连接事件
     * @param $ws
     * @param $request
     */
    public function onOpen($ws, $request) {
        var_dump($request->fd);
        if($request->fd == 1) {
            // 每2秒执行
            swoole_timer_tick(2000, function($timer_id){
                echo "2s: timerId:{$timer_id}\n";
            });
        }
    }
    /**
     * 监听ws消息事件
     * @param $ws
     * @param $frame
     */
    public function onMessage($ws, $frame) {
        echo "ser-push-message:{$frame->data}\n";
        // todo 10s
        $data = [
            'task' => 1,
            'fd' => $frame->fd,
        ];
        //$ws->task($data);
        swoole_timer_after(5000, function() use($ws, $frame) {
            echo "5s-after\n";
            $ws->push($frame->fd, "server-time-after:");
        });
        $ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));
    }
    /**
     * @param $serv
     * @param $taskId
     * @param $workerId
     * @param $data
     */
    public function onTask($serv, $taskId, $workerId, $data) {
        print_r($data);
        // 耗时场景 10s
        sleep(10);
        return "on task finish"; // 告诉worker
    }
    /**
     * @param $serv
     * @param $taskId
     * @param $data
     */
    public function onFinish($serv, $taskId, $data) {
        echo "taskId:{$taskId}\n";
        echo "finish-data-sucess:{$data}\n";
    }
    /**
     * close
     * @param $ws
     * @param $fd
     */
    public function onClose($ws, $fd) {
        echo "clientid:{$fd}\n";
    }
}
$obj = new Ws();

ws_server.php

<?php
$server = new swoole_websocket_server("0.0.0.0", 8812);
//$server->set([]);
$server->set(
    [
        'enable_static_handler' => true,
        'document_root' => "/home/work/hdtocs/swoole_mooc/data",
    ]
);
//监听websocket连接打开事件
$server->on('open', 'onOpen');
function onOpen($server, $request) {
    print_r($request->fd);
}
// 监听ws消息事件
$server->on('message', function (swoole_websocket_server $server, $frame) {
    echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
    $server->push($frame->fd, "singwa-push-secesss");
});
$server->on('close', function ($ser, $fd) {
    echo "client {$fd} closed\n";
});
$server->start();

目录

   └── client
       ├── tcp_client.php
   └── coroutine
       ├── redis.php
   └── io
       ├── 1.log
       ├── 1.txt
       ├── mysql.php
       ├── read.php
       ├── redis.php
       ├── write.php
   └── memory
       ├── table.php
   └── process
       ├── curl.php
       ├── process.php
   └── server
       ├── access.log
       ├── http_server.php
       ├── tcp.php
       ├── ws.php
       ├── ws_server.php