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

client

tcp_client.php

复制代码
  1. <?php
  2. // 连接 swoole tcp 服务
  3. $client = new swoole_client(SWOOLE_SOCK_TCP);
  4. if(!$client->connect("127.0.0.1", 9501)) {
  5. echo "连接失败";
  6. exit;
  7. }
  8. /// php cli常量
  9. fwrite(STDOUT, "请输入消息:");
  10. $msg = trim(fgets(STDIN));
  11. // 发送消息给 tcp server服务器
  12. $client->send($msg);
  13. // 接受来自server 的数据
  14. $result = $client->recv();
  15. echo $result;

coroutine

redis.php

复制代码
  1. <?php
  2. $http = new swoole_http_server('0.0.0.0', 8001);
  3. $http->on('request', function($request, $response) {
  4. // 获取redis 里面 的key的内容, 然后输出浏览器
  5. $redis = new Swoole\Coroutine\Redis();
  6. $redis->connect('127.0.0.1', 6379);
  7. $value = $redis->get($request->get['a']);
  8. $response->header("Content-Type", "text/plain");
  9. $response->end($value);
  10. });
  11. $http->start();

io

1.log

复制代码
  1. 20180306 18:08:4320180306 18:10:0720180306 18:10:0920180306 18:10:0920180306 18:10:39
  2. 20180306 18:10:40

1.txt

复制代码
  1. test-io

mysql.php

复制代码
  1. <?php
  2. class AysMysql {
  3. /**
  4. * @var string
  5. */
  6. public $dbSource = "";
  7. /**
  8. * mysql的配置
  9. * @var array
  10. */
  11. public $dbConfig = [];
  12. public function __construct() {
  13. //new swoole_mysql;
  14. $this->dbSource = new Swoole\Mysql;
  15. $this->dbConfig = [
  16. 'host' => '127.0.0.1',
  17. 'port' => 5123,
  18. 'user' => 'root',
  19. 'password' => 123456,
  20. 'database' => 'swoole',
  21. 'charset' => 'utf8',
  22. ];
  23. }
  24. public function update() {
  25. }
  26. public function add() {
  27. }
  28. /**
  29. * mysql 执行逻辑
  30. * @param $id
  31. * @param $username
  32. * @return bool
  33. */
  34. public function execute($id, $username) {
  35. // connect
  36. $this->dbSource->connect($this->dbConfig, function($db, $result) use($id, $username) {
  37. echo "mysql-connect".PHP_EOL;
  38. if($result === false) {
  39. var_dump($db->connect_error);
  40. // todo
  41. }
  42. //$sql = "select * from test where id=1";
  43. $sql = "update test set `username` = '".$username."' where id=".$id;
  44. // insert into
  45. // query (add select update delete)
  46. $db->query($sql, function($db, $result){
  47. // select => result返回的是 查询的结果内容
  48. if($result === false) {
  49. // todo
  50. var_dump($db->error);
  51. }elseif($result === true) {// add update delete
  52. // todo
  53. var_dump($db->affected_rows);
  54. }else {
  55. print_r($result);
  56. }
  57. $db->close();
  58. });
  59. });
  60. return true;
  61. }
  62. }
  63. $obj = new AysMysql();
  64. $flag = $obj->execute(1, 'singwa-111112');
  65. var_dump($flag).PHP_EOL;
  66. echo "start".PHP_EOL;
  67. for($i=0; $i<900000;$i++) {
  68. echo $i.PHP_EOL;
  69. }
  70. // 详情页 -》mysql(阅读数) -》msyql 文章 +1 -》页面数据呈现出来

read.php

复制代码
  1. <?php
  2. /**
  3. * 读取文件
  4. * __DIR__
  5. */
  6. $result = Swoole\Async::readfile(__DIR__."/1.txt", function($filename, $fileContent) {
  7. echo "filename:".$filename.PHP_EOL; // \n \r\n
  8. echo "content:".$fileContent.PHP_EOL;
  9. });
  10. var_dump($result);
  11. echo "start".PHP_EOL;

redis.php

复制代码
  1. <?php
  2. $redisClient = new swoole_redis;// Swoole\Redis
  3. $redisClient->connect('127.0.0.1', 6379, function(swoole_redis $redisClient, $result) {
  4. echo "connect".PHP_EOL;
  5. var_dump($result);
  6. // 同步 redis (new Redis())->set('key',2);
  7. /*$redisClient->set('singwa_1', time(), function(swoole_redis $redisClient, $result) {
  8. var_dump($result);
  9. });*/
  10. /*$redisClient->get('singwa_1', function(swoole_redis $redisClient, $result) {
  11. var_dump($result);
  12. $redisClient->close();
  13. });*/
  14. $redisClient->keys('*gw*', function(swoole_redis $redisClient, $result) {
  15. var_dump($result);
  16. $redisClient->close();
  17. });
  18. });
  19. echo "start".PHP_EOL;

write.php

复制代码
  1. <?php
  2. $content = date("Ymd H:i:s").PHP_EOL;
  3. swoole_async_writefile(__DIR__."/1.log", $content, function($filename){
  4. // todo
  5. echo "success".PHP_EOL;
  6. }, FILE_APPEND);
  7. // file_put_contents();
  8. echo "start".PHP_EOL;

memory

table.php

复制代码
  1. <?php
  2. // 创建内存表
  3. $table = new swoole_table(1024);
  4. // 内存表增加一列
  5. $table->column('id', $table::TYPE_INT, 4);
  6. $table->column('name', $table::TYPE_STRING, 64);
  7. $table->column('age', $table::TYPE_INT, 3);
  8. $table->create();
  9. $table->set('singwa_imooc', ['id' => 1, 'name'=> 'singwa', 'age' => 30]);
  10. // 另外一种方案
  11. $table['singwa_imooc_2'] = [
  12. 'id' => 2,
  13. 'name' => 'singwa2',
  14. 'age' => 31,
  15. ];
  16. $table->decr('singwa_imooc_2', 'age', 2);
  17. print_r($table['singwa_imooc_2']);
  18. echo "delete start:".PHP_EOL;
  19. $table->del('singwa_imooc_2');
  20. print_r($table['singwa_imooc_2']);

process

curl.php

复制代码
  1. <?php
  2. echo "process-start-time:".date("Ymd H:i:s");
  3. $workers = [];
  4. $urls = [
  5. 'http://baidu.com',
  6. 'http://sina.com.cn',
  7. 'http://qq.com',
  8. 'http://baidu.com?search=singwa',
  9. 'http://baidu.com?search=singwa2',
  10. 'http://baidu.com?search=imooc',
  11. ];
  12. for($i = 0; $i < 6; $i++) {
  13. // 子进程
  14. $process = new swoole_process(function(swoole_process $worker) use($i, $urls) {
  15. // curl
  16. $content = curlData($urls[$i]);
  17. //echo $content.PHP_EOL;
  18. $worker->write($content.PHP_EOL);
  19. }, true);
  20. $pid = $process->start();
  21. $workers[$pid] = $process;
  22. }
  23. foreach($workers as $process) {
  24. echo $process->read();
  25. }
  26. /**
  27. * 模拟请求URL的内容 1s
  28. * @param $url
  29. * @return string
  30. */
  31. function curlData($url) {
  32. // curl file_get_contents
  33. sleep(1);
  34. return $url . "success".PHP_EOL;
  35. }
  36. echo "process-end-time:".date("Ymd H:i:s");

process.php

复制代码
  1. <?php
  2. $process = new swoole_process(function(swoole_process $pro) {
  3. // todo
  4. // php redis.php
  5. $pro->exec("/home/work/study/soft/php/bin/php", [__DIR__.'/../server/http_server.php']);
  6. }, false);
  7. $pid = $process->start();
  8. echo $pid . PHP_EOL;
  9. swoole_process::wait();

server

access.log

http_server.php

复制代码
  1. <?php
  2. $http = new swoole_http_server("0.0.0.0", 8811);
  3. $http->set(
  4. [
  5. 'enable_static_handler' => true,
  6. 'document_root' => "/home/work/hdtocs/swoole_mooc/data",
  7. ]
  8. );
  9. $http->on('request', function($request, $response) {
  10. //print_r($request->get);
  11. $content = [
  12. 'date:' => date("Ymd H:i:s"),
  13. 'get:' => $request->get,
  14. 'post:' => $request->post,
  15. 'header:' => $request->header,
  16. ];
  17. swoole_async_writefile(__DIR__."/access.log", json_encode($content).PHP_EOL, function($filename){
  18. // todo
  19. }, FILE_APPEND);
  20. $response->cookie("singwa", "xsssss", time() + 1800);
  21. $response->end("sss". json_encode($request->get));
  22. });
  23. $http->start();

tcp.php

复制代码
  1. <?php
  2. //创建Server对象,监听 127.0.0.1:9501端口
  3. $serv = new swoole_server("127.0.0.1", 9501);
  4. $serv->set([
  5. 'worker_num' => 6 , // worker进程数 cpu 1-4
  6. 'max_request' => 10000,
  7. ]);
  8. //监听连接进入事件
  9. /**
  10. * $fd 客户端连接的唯一标示
  11. * $reactor_id 线程id
  12. */
  13. $serv->on('connect', function ($serv, $fd, $reactor_id) {
  14. echo "Client: {$reactor_id} - {$fd}-Connect.\n";
  15. });
  16. //监听数据接收事件
  17. $serv->on('receive', function ($serv, $fd, $reactor_id, $data) {
  18. $serv->send($fd, "Server: {$reactor_id} - {$fd}".$data);
  19. });
  20. //监听连接关闭事件
  21. $serv->on('close', function ($serv, $fd) {
  22. echo "Client: Close.\n";
  23. });
  24. //启动服务器
  25. $serv->start();

ws.php

复制代码
  1. <?php
  2. class Ws {
  3. CONST HOST = "0.0.0.0";
  4. CONST PORT = 8812;
  5. public $ws = null;
  6. public function __construct() {
  7. $this->ws = new swoole_websocket_server("0.0.0.0", 8812);
  8. $this->ws->set(
  9. [
  10. 'worker_num' => 2,
  11. 'task_worker_num' => 2,
  12. ]
  13. );
  14. $this->ws->on("open", [$this, 'onOpen']);
  15. $this->ws->on("message", [$this, 'onMessage']);
  16. $this->ws->on("task", [$this, 'onTask']);
  17. $this->ws->on("finish", [$this, 'onFinish']);
  18. $this->ws->on("close", [$this, 'onClose']);
  19. $this->ws->start();
  20. }
  21. /**
  22. * 监听ws连接事件
  23. * @param $ws
  24. * @param $request
  25. */
  26. public function onOpen($ws, $request) {
  27. var_dump($request->fd);
  28. if($request->fd == 1) {
  29. // 每2秒执行
  30. swoole_timer_tick(2000, function($timer_id){
  31. echo "2s: timerId:{$timer_id}\n";
  32. });
  33. }
  34. }
  35. /**
  36. * 监听ws消息事件
  37. * @param $ws
  38. * @param $frame
  39. */
  40. public function onMessage($ws, $frame) {
  41. echo "ser-push-message:{$frame->data}\n";
  42. // todo 10s
  43. $data = [
  44. 'task' => 1,
  45. 'fd' => $frame->fd,
  46. ];
  47. //$ws->task($data);
  48. swoole_timer_after(5000, function() use($ws, $frame) {
  49. echo "5s-after\n";
  50. $ws->push($frame->fd, "server-time-after:");
  51. });
  52. $ws->push($frame->fd, "server-push:".date("Y-m-d H:i:s"));
  53. }
  54. /**
  55. * @param $serv
  56. * @param $taskId
  57. * @param $workerId
  58. * @param $data
  59. */
  60. public function onTask($serv, $taskId, $workerId, $data) {
  61. print_r($data);
  62. // 耗时场景 10s
  63. sleep(10);
  64. return "on task finish"; // 告诉worker
  65. }
  66. /**
  67. * @param $serv
  68. * @param $taskId
  69. * @param $data
  70. */
  71. public function onFinish($serv, $taskId, $data) {
  72. echo "taskId:{$taskId}\n";
  73. echo "finish-data-sucess:{$data}\n";
  74. }
  75. /**
  76. * close
  77. * @param $ws
  78. * @param $fd
  79. */
  80. public function onClose($ws, $fd) {
  81. echo "clientid:{$fd}\n";
  82. }
  83. }
  84. $obj = new Ws();

ws_server.php

复制代码
  1. <?php
  2. $server = new swoole_websocket_server("0.0.0.0", 8812);
  3. //$server->set([]);
  4. $server->set(
  5. [
  6. 'enable_static_handler' => true,
  7. 'document_root' => "/home/work/hdtocs/swoole_mooc/data",
  8. ]
  9. );
  10. //监听websocket连接打开事件
  11. $server->on('open', 'onOpen');
  12. function onOpen($server, $request) {
  13. print_r($request->fd);
  14. }
  15. // 监听ws消息事件
  16. $server->on('message', function (swoole_websocket_server $server, $frame) {
  17. echo "receive from {$frame->fd}:{$frame->data},opcode:{$frame->opcode},fin:{$frame->finish}\n";
  18. $server->push($frame->fd, "singwa-push-secesss");
  19. });
  20. $server->on('close', function ($ser, $fd) {
  21. echo "client {$fd} closed\n";
  22. });
  23. $server->start();

目录

复制代码
  1. └── client
  2. ├── tcp_client.php
  3. └── coroutine
  4. ├── redis.php
  5. └── io
  6. ├── 1.log
  7. ├── 1.txt
  8. ├── mysql.php
  9. ├── read.php
  10. ├── redis.php
  11. ├── write.php
  12. └── memory
  13. ├── table.php
  14. └── process
  15. ├── curl.php
  16. ├── process.php
  17. └── server
  18. ├── access.log
  19. ├── http_server.php
  20. ├── tcp.php
  21. ├── ws.php
  22. ├── ws_server.php