stanley-king 3 lat temu
rodzic
commit
4daacdcb43
100 zmienionych plików z 2524 dodań i 89 usunięć
  1. 10 3
      core/framework/cache/cache.redis.php
  2. 25 7
      core/framework/core/base.php
  3. 26 0
      core/framework/libraries/CoMysqliPool.php
  4. 1 1
      core/framework/libraries/CoPool.php
  5. 89 18
      core/framework/libraries/CoRefPool.php
  6. 2 1
      core/framework/libraries/cache.php
  7. 19 2
      core/framework/libraries/model.php
  8. 1 3
      docker/compose/stanley/docker-compose.yml
  9. 1 1
      fooder.php
  10. 1 0
      h5py
  11. 17 15
      helper/queue/iqueue.php
  12. 88 27
      helper/refill/util.php
  13. BIN
      plot/__pycache__/DataCenter.cpython-37.pyc
  14. BIN
      plot/__pycache__/MchDataCenter.cpython-37.pyc
  15. BIN
      plot/__pycache__/Singleton.cpython-37.pyc
  16. BIN
      plot/__pycache__/plog.cpython-37.pyc
  17. BIN
      plot/__pycache__/thdf5.cpython-37.pyc
  18. 8 6
      rdispatcher/coall.php
  19. 1 0
      rdispatcher/codispatcher.php
  20. 94 0
      server/comysqli.php
  21. 10 4
      server/coredis_test.php
  22. 1 1
      test/TestRefillThird.php
  23. 8 0
      test/examples/atomic/long.php
  24. 7 0
      test/examples/atomic/test.php
  25. 16 0
      test/examples/atomic/wait.php
  26. 28 0
      test/examples/c10k.php
  27. 53 0
      test/examples/client/async.php
  28. 33 0
      test/examples/client/get_socket.php
  29. 18 0
      test/examples/client/long_tcp.php
  30. 32 0
      test/examples/client/select.php
  31. 29 0
      test/examples/client/sync.php
  32. 9 0
      test/examples/client/test.txt
  33. 23 0
      test/examples/client/udp_async.php
  34. 10 0
      test/examples/client/udp_sync.php
  35. 21 0
      test/examples/client2.php
  36. 117 0
      test/examples/coroutine/TestHttpServ.php
  37. 59 0
      test/examples/coroutine/backtrace.php
  38. 25 0
      test/examples/coroutine/before_server_start.php
  39. 18 0
      test/examples/coroutine/behavior/do-while.php
  40. 27 0
      test/examples/coroutine/behavior/for.php
  41. 14 0
      test/examples/coroutine/behavior/foreach.php
  42. 14 0
      test/examples/coroutine/behavior/goto.php
  43. 24 0
      test/examples/coroutine/behavior/preemptive_timer.php
  44. 32 0
      test/examples/coroutine/behavior/tick.php
  45. 35 0
      test/examples/coroutine/behavior/while.php
  46. 27 0
      test/examples/coroutine/behavior/while2.php
  47. 32 0
      test/examples/coroutine/channel/test.php
  48. 27 0
      test/examples/coroutine/client_send_yield.php
  49. 27 0
      test/examples/coroutine/client_send_yield_server.php
  50. 19 0
      test/examples/coroutine/coro_array_map.php
  51. 19 0
      test/examples/coroutine/coro_call_user.php
  52. 25 0
      test/examples/coroutine/coro_channel.php
  53. 28 0
      test/examples/coroutine/coro_destruct.php
  54. 32 0
      test/examples/coroutine/coro_destuct.php
  55. 7 0
      test/examples/coroutine/coro_empty.php
  56. 11 0
      test/examples/coroutine/coro_gethost.php
  57. 9 0
      test/examples/coroutine/coro_include.php
  58. 22 0
      test/examples/coroutine/coro_invoke.php
  59. 17 0
      test/examples/coroutine/coro_nested.php
  60. 16 0
      test/examples/coroutine/coro_nested_empty.php
  61. 39 0
      test/examples/coroutine/coro_serialize.php
  62. 10 0
      test/examples/coroutine/coro_set_stack_size.php
  63. 9 0
      test/examples/coroutine/coro_sleep.php
  64. 19 0
      test/examples/coroutine/coro_stackless.php
  65. 16 0
      test/examples/coroutine/coro_util.php
  66. 40 0
      test/examples/coroutine/csp.php
  67. 11 0
      test/examples/coroutine/deadlock.php
  68. 27 0
      test/examples/coroutine/defer.php
  69. 79 0
      test/examples/coroutine/defer_client.php
  70. 27 0
      test/examples/coroutine/enable_coroutine.php
  71. 14 0
      test/examples/coroutine/exception/empty.php
  72. 5 0
      test/examples/coroutine/exec.php
  73. 26 0
      test/examples/coroutine/exit_in_coroutine.php
  74. 12 0
      test/examples/coroutine/exit_with_status.php
  75. 20 0
      test/examples/coroutine/fgets.php
  76. 11 0
      test/examples/coroutine/fread.php
  77. 10 0
      test/examples/coroutine/fwrite.php
  78. 7 0
      test/examples/coroutine/gethostbyname.php
  79. 53 0
      test/examples/coroutine/http/server.php
  80. 81 0
      test/examples/coroutine/http2_client.php
  81. 40 0
      test/examples/coroutine/http_backend_serv.php
  82. 12 0
      test/examples/coroutine/http_client.php
  83. 13 0
      test/examples/coroutine/http_download.php
  84. 37 0
      test/examples/coroutine/http_server.php
  85. 162 0
      test/examples/coroutine/httpmulti.php
  86. 40 0
      test/examples/coroutine/library/base.php
  87. 21 0
      test/examples/coroutine/list_coroutines.php
  88. 32 0
      test/examples/coroutine/mysql_chan.php
  89. 16 0
      test/examples/coroutine/mysql_escape.php
  90. 14 0
      test/examples/coroutine/mysql_execute_empty.php
  91. 41 0
      test/examples/coroutine/mysql_prepare.php
  92. 24 0
      test/examples/coroutine/mysql_prepare_2.php
  93. 28 0
      test/examples/coroutine/mysql_procedure_exec.php
  94. 26 0
      test/examples/coroutine/mysql_query.php
  95. 15 0
      test/examples/coroutine/mysql_unixsocket.php
  96. 20 0
      test/examples/coroutine/proc_open.php
  97. 71 0
      test/examples/coroutine/reconnect_test.php
  98. 8 0
      test/examples/coroutine/redis/auth.php
  99. 24 0
      test/examples/coroutine/redis/defer.php
  100. 0 0
      test/examples/coroutine/redis/eval.php

+ 10 - 3
core/framework/cache/cache.redis.php

@@ -28,7 +28,7 @@ class Cacheredis extends Cache
 
     public function __destruct()
     {
-        if(defined('USE_COROUTINE') && USE_COROUTINE && defined(COROUTINE_HOOK_TCP) && COROUTINE_HOOK_TCP)
+        if(defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP)
         {
             if(!CoRedisPool::instance()->stoped())
             {
@@ -48,7 +48,7 @@ class Cacheredis extends Cache
 
     private function init_master()
     {
-        if(defined('USE_COROUTINE') && USE_COROUTINE)
+        if(defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP)
         {
             if (!is_null($this->master))
             {
@@ -100,7 +100,7 @@ class Cacheredis extends Cache
 
     private function init_slave()
     {
-        if(defined('USE_COROUTINE') && USE_COROUTINE)
+        if(defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP)
         {
             if (!is_null($this->slave))
             {
@@ -364,4 +364,11 @@ class Cacheredis extends Cache
         if (!$this->enable) return false;
         return $this->handler->lLen($key);
     }
+
+    public function lpush($queue_name,$value)
+    {
+        $this->init_master();
+        if (!$this->enable) return false;
+        return $this->handler->lPush($queue_name, $value);
+    }
 }

+ 25 - 7
core/framework/core/base.php

@@ -252,21 +252,39 @@ final class Base
 	public static function mobile_autoload($class)
 	{
 		$class = strtolower($class);
-		if (ucwords(substr($class,-5)) == 'Class' ){
+		if (ucwords(substr($class,-5)) == 'Class' )
+		{
 			if (!@include_once(BASE_PATH.'/framework/libraries/'.substr($class,0,-5).'.class.php')){
 				throw new Exception("Class Error: {$class}.isn't exists!");
 			}
-		} elseif (ucwords(substr($class,0,5)) == 'Cache' && $class != 'cache'){
-            $file = BASE_CORE_PATH.'/framework/cache/'.substr($class,0,5).'.'.substr($class,5).'.php';
-            $x = file_exists($file);
+		}
+		elseif (ucwords(substr($class,0,5)) == 'Cache' && $class != 'cache')
+        {
 			if (!@include_once(BASE_CORE_PATH.'/framework/cache/'.substr($class,0,5).'.'.substr($class,5).'.php')){
 				throw new Exception("Class Error: {$class}.isn't exists!");
 			}
-		} elseif ($class == 'db'){
-			if (!@include_once(BASE_CORE_PATH.'/framework/db/'.strtolower(DBDRIVER).'.php')){
+		}
+		elseif ($class == 'db')
+        {
+            if(defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP)
+            {
+                if(strtolower(DBDRIVER) == 'mysqli') {
+                    $driver = 'comysqli';
+                }
+                else {
+                    $driver = DBDRIVER;
+                }
+            }
+            else {
+                $driver = DBDRIVER;
+            }
+
+			if (!@include_once(BASE_CORE_PATH.'/framework/db/'.strtolower($driver).'.php')) {
 				throw new Exception("Class Error: {$class}.isn't exists!");
 			}
-		} elseif (!@include_once(BASE_CORE_PATH.'/framework/libraries/'.$class.'.php')){
+		}
+		elseif (!@include_once(BASE_CORE_PATH.'/framework/libraries/'.$class.'.php'))
+        {
             throw new Exception("Class Error: {$class} isn't exists!");
         }
 	}

+ 26 - 0
core/framework/libraries/CoMysqliPool.php

@@ -0,0 +1,26 @@
+<?php
+
+class CoMysqliPool extends CoRefPool
+{
+    const max_clients = 10;
+
+    private static $stInstance = null;
+
+    public static function instance()
+    {
+        if (self::$stInstance == null) {
+            self::$stInstance = new CoMysqliPool();
+        }
+        return self::$stInstance;
+    }
+
+    private function __construct()
+    {
+        parent::__construct(self::max_clients);
+    }
+
+    public function create_client()
+    {
+        return ['master' => null, 'slave' => null];
+    }
+}

+ 1 - 1
core/framework/libraries/CoPool.php

@@ -50,7 +50,7 @@ abstract class CoPool
         }
         $count = count($this->mFreeClients);
         $waitings = count($this->mSuspendCIDS);
-        Log::record("put cid = {$cid} mUsingCount={$this->mUsingCount} frees={$count} waitings={$waitings}",Log::DEBUG);
+        Log::record("resume cid={$cid} mUsingCount={$this->mUsingCount} frees={$count} waitings={$waitings}",Log::DEBUG);
     }
 
     private function getSuspend()

+ 89 - 18
core/framework/libraries/CoRefPool.php

@@ -21,17 +21,18 @@ abstract class CoRefPool
     {
         if(array_key_exists($cid,$this->mUsingClients)) {
             $this->mUsingClients[$cid]['ref_count'] += 1;
-            return $this->mUsingClients[$cid]['object'];
+            return $this->mUsingClients[$cid]['client'];
         }
 
         if(!empty($this->mFreeClients)) {
             $client = $this->mFreeClients[0];
             unset($this->mFreeClients[0]);
             $this->mFreeClients = array_values($this->mFreeClients);
-            $this->mUsingClients[$cid] = ['object' =>$client,'ref_count' => 1];
+            $this->mUsingClients[$cid] = ['client' => $client, 'ref_count' => 1,'ifTransacting' => false];
         }
         elseif(count($this->mUsingClients) < $this->mMaxClient) {
-            $client = $this->create_client($args);
+            $client = $this->create_client();
+            $this->mUsingClients[$cid] = ['client' => $client, 'ref_count' => 1,'ifTransacting' => false];
         }
         else {
             $this->mSuspendCIDS[] = Co::getCid();
@@ -39,38 +40,108 @@ abstract class CoRefPool
             $client = $this->mFreeClients[0];
             unset($this->mFreeClients[0]);
             $this->mFreeClients = array_values($this->mFreeClients);
+            $this->mUsingClients[$cid] = ['client' => $client, 'ref_count' => 1,'ifTransacting' => false];
         }
-        $this->mUsingCount++;
 
-        Log::record("get mUsingCount={$this->mUsingCount}",Log::DEBUG);
+        $count = count($this->mUsingClients);
+        Log::record("get mUsingCount={$count}",Log::DEBUG);
+
         return $client;
     }
 
-    public function put($client) {
+    public function find($cid)
+    {
+        if(array_key_exists($cid,$this->mUsingClients)) {
+            return $this->mUsingClients[$cid]['client'];
+        } else {
+            Log::record(__METHOD__ . " cannot find mysqli cid={$cid} client",Log::DEBUG);
+            throw new Exception("cannot find mysqli cid={$cid} client");
+        }
+    }
 
-        $this->mFreeClients[] = $client;
-        $this->mUsingCount--;
-        $cid = $this->getSuspend();
-        if($cid > 0) {
-            Co::resume($cid);
+    public function reset($cid,$client)
+    {
+        if(array_key_exists($cid,$this->mUsingClients)) {
+            return $this->mUsingClients[$cid]['client'] = $client;
+        } else {
+            Log::record(__METHOD__ . " cannot find mysqli cid={$cid} client",Log::DEBUG);
+            throw new Exception("cannot find mysqli cid={$cid} client");
         }
-        $count = count($this->mFreeClients);
-        $waitings = count($this->mSuspendCIDS);
-        Log::record("put cid = {$cid} mUsingCount={$this->mUsingCount} frees={$count} waitings={$waitings}",Log::DEBUG);
     }
 
-    private function getSuspend()
+    public function transaction($cid)
     {
-        if(empty($this->mSuspendCIDS)) {
-            return 0;
+        if(array_key_exists($cid,$this->mUsingClients)) {
+            return $this->mUsingClients[$cid]['ifTransacting'];
+        } else {
+            Log::record(__METHOD__ . " cannot find mysqli cid={$cid} client",Log::DEBUG);
+            throw new Exception("cannot find mysqli cid={$cid} client");
+        }
+    }
+
+    public function commit($cid)
+    {
+        if(array_key_exists($cid,$this->mUsingClients)) {
+            return $this->mUsingClients[$cid]['ifTransacting'] = false;
+        } else {
+            Log::record(__METHOD__ . " cannot find mysqli cid={$cid} client",Log::DEBUG);
+            throw new Exception("cannot find mysqli cid={$cid} client");
+        }
+    }
+
+    public function rollback($cid)
+    {
+        if(array_key_exists($cid,$this->mUsingClients)) {
+            return $this->mUsingClients[$cid]['ifTransacting'] = false;
+        } else {
+            Log::record(__METHOD__ . " cannot find mysqli cid={$cid} client",Log::DEBUG);
+            throw new Exception("cannot find mysqli cid={$cid} client");
+        }
+    }
+
+    public function put($cid)
+    {
+        Log::record("CoRefPool put cid={$cid}",Log::DEBUG);
+        if(array_key_exists($cid,$this->mUsingClients))
+        {
+            $this->mUsingClients[$cid]['ref_count'] -= 1;
+            $refcount = $this->mUsingClients[$cid]['ref_count'];
+
+            if($refcount == 0)
+            {
+                $client = $this->mUsingClients[$cid]['client'];
+                unset($this->mUsingClients[$cid]);
+
+                $this->mFreeClients[] = $client;
+                $suspend_cid = $this->getSuspend();
+                if($suspend_cid > 0) {
+                    Co::resume($suspend_cid);
+                }
+
+                Log::record("CoRefPool put cid={$cid} suspend_cid={$suspend_cid} refcount={$refcount}",Log::DEBUG);
+            }
+            else {
+                Log::record("CoRefPool put cid={$cid} refcount={$refcount}",Log::DEBUG);
+            }
         }
         else {
+            Log::record(__METHOD__ . " cannot find mysqli cid={$cid} client",Log::DEBUG);
+            throw new Exception("cannot find mysqli cid={$cid} client");
+        }
+    }
+
+    private function getSuspend()
+    {
+        if (empty($this->mSuspendCIDS)) {
+            return 0;
+        } else {
             $cid = $this->mSuspendCIDS[0];
             unset($this->mSuspendCIDS[0]);
             $this->mSuspendCIDS = array_values($this->mSuspendCIDS);
             return $cid;
         }
     }
+
     public function stoped() {
         return $this->mStop;
     }
@@ -78,5 +149,5 @@ abstract class CoRefPool
         $this->mStop = true;
     }
 
-    abstract public function create_client($args);
+    abstract public function create_client();
 }

+ 2 - 1
core/framework/libraries/cache.php

@@ -36,7 +36,8 @@ class Cache
 	 */
 	public static function getInstance()
     {
-        if (defined('USE_COROUTINE') && USE_COROUTINE && defined(COROUTINE_HOOK_TCP) && COROUTINE_HOOK_TCP) {
+        if(defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP)
+        {
             $args = func_get_args();
             return CoRedisPool::instance()->get($args);
         } else {

+ 19 - 2
core/framework/libraries/model.php

@@ -81,12 +81,27 @@ class Model
 
 	public function __construct($table = null)
     {
+        if(defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP)
+        {
+            $cid = Co::getCid();
+            CoMysqliPool::instance()->get($cid);
+        }
+
         $this->table_prefix = DBPRE;
         $this->init($table);
 	}
+
 	public function __destruct()
     {
         Log::record("{$this->table_name} __destruct",Log::DEBUG);
+        if(defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP)
+        {
+            if(!CoMysqliPool::instance()->stoped())
+            {
+                $cid = Co::getCid();
+                CoMysqliPool::instance()->put($cid);
+            }
+        }
     }
 
     public function init($table)
@@ -453,7 +468,8 @@ class Model
 	 * @param array $options
 	 * @return boolean
 	 */
-    public function update($data='',$options= []) {
+    public function update($data='',$options= [])
+    {
         if(empty($data)) return false;
         // 分析表达式
         $options =  $this->parse_options($options);
@@ -673,7 +689,8 @@ class Model
     * @param array $data
     * @return array
     */
-     protected function chk_field($data) {
+     protected function chk_field($data)
+     {
         if(!empty($this->fields[$this->table_name])) {
             foreach ($data as $key=>$val){
                 if(!in_array($key,$this->fields[$this->table_name],true)){

+ 1 - 3
docker/compose/stanley/docker-compose.yml

@@ -231,7 +231,7 @@ services:
       - "websrv"
       - "searcher"
 
-  phpswool:
+  phpswoole:
     image: php-swool-redis:latest
     volumes:
       - ../../conf/etc/localtime:/etc/localtime:ro
@@ -242,8 +242,6 @@ services:
     container_name: "panda-swoole"
     depends_on:
       - "redisrv"
-      - "websrv"
-      - "searcher"
 
   flasksrv:
     image: pycpu:3.7.10

+ 1 - 1
fooder.php

@@ -15,7 +15,7 @@ require_once(BASE_CORE_PATH . '/framework/libraries/queue.php');
 require_once(BASE_CORE_PATH . '/framework/libraries/language.php');
 require_once(BASE_CORE_PATH . '/framework/libraries/model.php');
 require_once(BASE_CORE_PATH . '/framework/libraries/log.php');
-require_once(BASE_CORE_PATH . '/framework/db/mysqli.php');
+//require_once(BASE_CORE_PATH . '/framework/db/mysqli.php');
 require_once(BASE_CORE_PATH . '/framework/function/goods.php');
 require_once(BASE_CORE_PATH . '/framework/libraries/validator.php');
 require_once(BASE_CORE_PATH . '/framework/libraries/resizeimage.php');

+ 1 - 0
h5py

@@ -0,0 +1 @@
+Subproject commit 514deb9838453e53442bb9451ce93c3b26c8fc01

+ 17 - 15
helper/queue/iqueue.php

@@ -79,7 +79,6 @@ class IQueueDB
         {
             if($this->connect()) {
                 $ret = $this->_redis->rPush($this->_queue_name, $value);
-                Log::record("IQueueDB::lpush ret={$ret}", Log::DEBUG);
                 return $ret;
             } else {
                 Log::record("IQueueDB::rpush connect=false", Log::DEBUG);
@@ -98,7 +97,6 @@ class IQueueDB
         {
             if ($this->connect()) {
                 $ret = $this->_redis->lPush($this->_queue_name, $value);
-                Log::record("IQueueDB::lpush ret={$ret}", Log::DEBUG);
                 return $ret;
             } else {
                 Log::record("IQueueDB::lpush connect=false", Log::DEBUG);
@@ -133,10 +131,6 @@ class IQueueDB
     public function brpop($key, $time)
     {
         $result = $this->_redis->brPop($key, $time);
-
-        $tmp = serialize($result);
-        Log::record("IQueueDB::brPop={$tmp}",Log::DEBUG);
-
         if ($result) {
             return $result[1];
         } else {
@@ -146,10 +140,6 @@ class IQueueDB
     public function blpop($key, $time)
     {
         $result = $this->_redis->blPop($key, $time);
-
-        $tmp = serialize($result);
-        Log::record("IQueueDB::blPop={$tmp}",Log::DEBUG);
-
         if ($result) {
             return $result[1];
         } else {
@@ -248,7 +238,7 @@ abstract class ILooper
 {
     private $_stop = false;
     private $mServer;
-    const MAX_COROUTINE = 100;
+    const MAX_COROUTINE = 10000;
 
     protected function __construct($server)
     {
@@ -296,10 +286,20 @@ abstract class ILooper
                             continue;
                         }
 
-                        $content = $this->mServer->rpop();
-                        if(empty($content)) {
-                            Swoole\Coroutine::sleep(1);
-                            continue;
+                        if(defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP)
+                        {
+                            $content = $this->mServer->brpop($queues,1);
+                            if(empty($content)) {
+                                continue;
+                            }
+                        }
+                        else
+                        {
+                            $content = $this->mServer->rpop();
+                            if(empty($content)) {
+                                Swoole\Coroutine::sleep(1);
+                                continue;
+                            }
                         }
 
                         if($this->_stop)
@@ -313,7 +313,9 @@ abstract class ILooper
                             go(function ()use ($content,$num,$mem) {
                                 $start = microtime(true);
                                 Log::record("BeginGoFunction coroutin_num={$num} memory={$mem}",Log::DEBUG);
+
                                 $method = $this->handle($content);
+
                                 $use_time = microtime(true) - $start;
                                 $msg = sprintf("EndGoFunction coroutin_num={$num} memory={$mem} request_time=%.6f method={$method}",$use_time);
                                 Log::record($msg,Log::DEBUG);

+ 88 - 27
helper/refill/util.php

@@ -222,60 +222,97 @@ class util
 
     public static function push_add($params)
     {
-        try {
-            $ret = queue\DispatcherClient::instance()->push('add', $params);
+        try
+        {
+            if(defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
+                $ret = self::push_queue('add', $params);
+            } else {
+                $ret = queue\DispatcherClient::instance()->push('add', $params);
+            }
+
             return $ret !== false;
-        } catch (Exception $ex) {
+        }
+        catch (Exception $ex) {
             return false;
         }
     }
 
     public static function push_add_zero($params)
     {
-        try {
-            $ret = queue\DispatcherClient::instance()->push('add_zero', $params);
+        try
+        {
+            if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
+                $ret = self::push_queue('add_zero', $params);
+            } else {
+                $ret = queue\DispatcherClient::instance()->push('add_zero', $params);
+            }
             return $ret !== false;
-        } catch (Exception $ex) {
+        }
+        catch (Exception $ex) {
             return false;
         }
     }
 
     public static function push_addthird($params)
     {
-        try {
-            $ret = queue\DispatcherClient::instance()->push('addthird', $params);
+        try
+        {
+            if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
+                $ret = self::push_queue('addthird', $params);
+            } else {
+                $ret = queue\DispatcherClient::instance()->push('addthird', $params);
+            }
             return $ret !== false;
-        } catch (Exception $ex) {
+        }
+        catch (Exception $ex) {
             return false;
         }
     }
 
     public static function push_notify($chname, $params)
     {
-        try {
-            $ret = queue\DispatcherClient::instance()->push('notify', ['channel' => $chname, 'params' => $params]);
+        try
+        {
+            if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
+                $ret = self::push_queue('notify', ['channel' => $chname, 'params' => $params]);
+            } else {
+                $ret = queue\DispatcherClient::instance()->push('notify', ['channel' => $chname, 'params' => $params]);
+            }
             return $ret !== false;
-        } catch (Exception $ex) {
+        }
+        catch (Exception $ex) {
             return false;
         }
     }
 
     public static function push_notify_merchant($order_id, $manual)
     {
-        try {
-            $ret = queue\DispatcherClient::instance()->push('notify_mechant', ['order_id' => $order_id, 'manual' => $manual]);
+        try
+        {
+            if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
+                $ret = self::push_queue('notify_mechant', ['order_id' => $order_id, 'manual' => $manual]);
+            } else {
+                $ret = queue\DispatcherClient::instance()->push('notify_mechant', ['order_id' => $order_id, 'manual' => $manual]);
+            }
             return $ret !== false;
-        } catch (Exception $ex) {
+        }
+        catch (Exception $ex) {
             return false;
         }
     }
 
     public static function push_query($order_id)
     {
-        try {
-            $ret = queue\DispatcherClient::instance()->push('query', ['order_id' => $order_id]);
+        try
+        {
+            if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
+                $ret = self::push_queue('query', ['order_id' => $order_id]);
+            } else {
+                $ret = queue\DispatcherClient::instance()->push('query', ['order_id' => $order_id]);
+            }
             return $ret !== false;
-        } catch (Exception $ex) {
+        }
+        catch (Exception $ex) {
             return false;
         }
     }
@@ -283,33 +320,57 @@ class util
     public static function push_query_net($order_id)
     {
         try {
-            $ret = queue\DispatcherClient::instance()->push('query_net', ['order_id' => $order_id]);
+            if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
+                $ret = self::push_queue('query_net', ['order_id' => $order_id]);
+            } else {
+                $ret = queue\DispatcherClient::instance()->push('query_net', ['order_id' => $order_id]);
+            }
             return $ret !== false;
-        } catch (Exception $ex) {
+        }
+        catch (Exception $ex) {
             return false;
         }
     }
 
     public static function manual_success($order_id)
     {
-        try {
-            $ret = queue\DispatcherClient::instance()->push('manual_success', ['order_id' => $order_id]);
+        try
+        {
+            if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
+                $ret = self::push_queue('manual_success', ['order_id' => $order_id]);
+            } else {
+                $ret = queue\DispatcherClient::instance()->push('manual_success', ['order_id' => $order_id]);
+            }
             return $ret !== false;
-        } catch (Exception $ex) {
+        }
+        catch (Exception $ex) {
             return false;
         }
     }
 
     public static function manual_cancel($order_id)
     {
-        try {
-            $ret = queue\DispatcherClient::instance()->push('manual_cancel', ['order_id' => $order_id]);
+        try
+        {
+            if (defined('USE_COROUTINE') && USE_COROUTINE && defined('COROUTINE_HOOK_TCP') && COROUTINE_HOOK_TCP) {
+                $ret = self::push_queue('manual_cancel', ['order_id' => $order_id]);
+            } else {
+                $ret = queue\DispatcherClient::instance()->push('manual_cancel', ['order_id' => $order_id]);
+            }
             return $ret !== false;
-        } catch (Exception $ex) {
+        }
+        catch (Exception $ex) {
             return false;
         }
     }
 
+    private static function push_queue($method, $value)
+    {
+        $queue_name = 'QUEUE_DISPATCHER_CO';
+        $ins = Cache::getInstance('cacheredis');
+        return $ins->lpush($queue_name, serialize([$method => $value]));
+    }
+
     public static function dispatcher_queue_length()
     {
         $ins = Cache::getInstance('cacheredis');
@@ -526,4 +587,4 @@ class util
             return false;
         }
     }
-}
+}

BIN
plot/__pycache__/DataCenter.cpython-37.pyc


BIN
plot/__pycache__/MchDataCenter.cpython-37.pyc


BIN
plot/__pycache__/Singleton.cpython-37.pyc


BIN
plot/__pycache__/plog.cpython-37.pyc


BIN
plot/__pycache__/thdf5.cpython-37.pyc


+ 8 - 6
rdispatcher/coall.php

@@ -5,8 +5,7 @@ define('APP_ID', 'coall');
 define('MOBILE_SERVER',true);
 define('USE_COROUTINE',true);
 define('SUPPORT_PTHREAD',false);
-
-
+define('COROUTINE_HOOK_TCP',true);
 define('BASE_ROOT_PATH',str_replace('/rdispatcher','',dirname(__FILE__)));
 define('BASE_PATH',BASE_ROOT_PATH . '/rdispatcher');
 
@@ -20,6 +19,11 @@ require_once(BASE_HELPER_PATH . '/refill/RefillFactory.php');
 require_once(BASE_PATH . '/processor.php');
 require_once(BASE_PATH . '/proxy.php');
 
+require_once(BASE_CORE_PATH . '/framework/libraries/CoRefPool.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/CoMysqliPool.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/CoPool.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/CoRedisPool.php');
+
 Co::set(['hook_flags' => SWOOLE_HOOK_NATIVE_CURL | SWOOLE_HOOK_SLEEP | SWOOLE_HOOK_TCP]);
 if (empty($_SERVER['argv'][1])) exit('parameter error');
 $process_count = intval($_SERVER['argv'][1]);
@@ -78,7 +82,6 @@ function subscribe_message(&$quit, &$redis, $channels)
                         refill\RefillFactory::instance()->load();
                     }
                     elseif($type == 'ratio') {
-                        $start = microtime(true);
                         $ins = Cache::getInstance('cacheredis');
                         $val = $ins->get_org('channel_ratios');
 
@@ -89,9 +92,6 @@ function subscribe_message(&$quit, &$redis, $channels)
                         if(empty($ratios)) continue;
 
                         refill\RefillFactory::instance()->UpdateRatio($ratios);
-                        $use_time = microtime(true) - $start;
-                        $msg = sprintf("subscribe_message UpdateRatio use_time=%.6f",$use_time);
-                        Log::record($msg,Log::DEBUG);
                     }
                     else {
                         Log::record("subscribe_message dont not handle mgs:{$sub_type}-{$channel}-{$type}",Log::DEBUG);
@@ -153,6 +153,8 @@ for ($i = 0; $i < $process_count;$i++)
                 }
                 Log::record("coroutine_num = {$num}",Log::DEBUG);
             } while($num > 1);
+            CoRedisPool::instance()->stop();
+            CoMysqliPool::instance()->stop();
         });
 
     }, false, false, true);

+ 1 - 0
rdispatcher/codispatcher.php

@@ -20,6 +20,7 @@ require_once(BASE_HELPER_PATH . '/refill/RefillFactory.php');
 require_once(BASE_PATH . '/processor.php');
 require_once(BASE_PATH . '/proxy.php');
 
+
 Co::set(['hook_flags' => SWOOLE_HOOK_NATIVE_CURL|SWOOLE_HOOK_SLEEP]);
 if (empty($_SERVER['argv'][1])) exit('parameter error');
 $process_count = intval($_SERVER['argv'][1]);

+ 94 - 0
server/comysqli.php

@@ -0,0 +1,94 @@
+<?php
+declare(strict_types=0);
+
+define('MOBILE_SERVER', true);
+define('USE_COROUTINE', true);
+define('SUPPORT_PTHREAD', false);
+
+define('APP_ID', 'comysqli');
+define('BASE_ROOT_PATH', str_replace('/server', '', dirname(__FILE__)));
+define('BASE_PATH', BASE_ROOT_PATH . '/server');
+define('COROUTINE_HOOK_TCP',true);
+
+require_once(BASE_ROOT_PATH . '/global.php');
+require_once(BASE_ROOT_PATH . '/fooder.php');
+require_once(BASE_HELPER_PATH . '/refill_proxy.php');
+require_once(BASE_CORE_PATH . '/framework/function/http.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/CoRefPool.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/CoMysqliPool.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/CoPool.php');
+require_once(BASE_CORE_PATH . '/framework/libraries/CoRedisPool.php');
+
+Co::set(['hook_flags' => SWOOLE_HOOK_NATIVE_CURL | SWOOLE_HOOK_SLEEP | SWOOLE_HOOK_TCP]);
+
+class MysqliPoolTest
+{
+    public function setval()
+    {
+        for ($i = 0; $i < 20; $i++)
+        {
+            Log::record("cur index = {$i}",Log::DEBUG);
+            go(function ()
+            {
+                $mod_order = Model('vr_order');
+                $order_info = $mod_order->getOrderInfo(['order_sn' => '4694820679086133084177']);
+
+                $mod_orderx = Model('vr_order');
+                $order_info = $mod_orderx->getOrderInfo(['order_sn' => '4694820679086133084177']);
+            });
+        }
+    }
+
+    public function readval()
+    {
+        for ($i = 0; $i < 20; $i++)
+        {
+            Log::record("cur index = {$i}",Log::DEBUG);
+            go(function ()
+            {
+                $mod_order = Model('vr_order');
+                $order_info = $mod_order->getOrderInfo(['order_sn' => '4694820679086133084177']);
+
+                $mod_orderx = Model('vr_order');
+                $order_info = $mod_orderx->getOrderInfo(['order_sn' => '4694820679086133084177']);
+            });
+        }
+    }
+}
+
+Swoole\Coroutine::set(['max_coroutine' => 500]);
+
+go(function ()
+{
+    Base::run_util();
+
+    $mod_order = Model('vr_order');
+    $order_info = $mod_order->getOrderInfo(['order_sn' => '4694820679086133084177']);
+
+    $test = new MysqliPoolTest();
+
+    for ($i = 0; $i < 100; $i++)
+    {
+        Log::record("cur index = {$i}",Log::DEBUG);
+        go(function () use($test)
+        {
+            $test->setval();
+        });
+        sleep(1);
+    }
+
+    for ($i = 0; $i < 100; $i++)
+    {
+        go(function () use($test)
+        {
+            $test->readval();
+        });
+        sleep(1);
+    }
+
+    sleep(10);
+    CoRedisPool::instance()->stop();
+    CoMysqliPool::instance()->stop();
+});
+
+//docker-compose run phpswoole php /var/www/html/server/comysqli.php

+ 10 - 4
server/coredis_test.php

@@ -25,7 +25,7 @@ class RedisPoolTest
 {
     public function setval()
     {
-        for ($i = 0; $i < 20000; $i++)
+        for ($i = 0; $i < 200; $i++)
         {
             Log::record("cur index = {$i}",Log::DEBUG);
             go(function ()
@@ -40,7 +40,7 @@ class RedisPoolTest
 
     public function readval()
     {
-        for ($i = 0; $i < 20000; $i++)
+        for ($i = 0; $i < 200; $i++)
         {
             Log::record("cur index = {$i}",Log::DEBUG);
             go(function ()
@@ -60,11 +60,16 @@ go(function ()
 {
     Base::run_util();
 
+    $key = '100905';
+    $ins = Cache::getInstance('cacheredis');
+    $ret = $ins->incr($key);
+    Log::record("setval value={$ret}",Log::DEBUG);
+
     $test = new RedisPoolTest();
 
     for ($i = 0; $i < 100; $i++)
     {
-        Log::record("cur index = {$i}",Log::DEBUG);
+        Log::record("first index = {$i}",Log::DEBUG);
         go(function () use($test)
         {
             $test->setval();
@@ -74,6 +79,7 @@ go(function ()
 
     for ($i = 0; $i < 100; $i++)
     {
+        Log::record("second index = {$i}",Log::DEBUG);
         go(function () use($test)
         {
             $test->readval();
@@ -85,7 +91,7 @@ go(function ()
     CoRedisPool::instance()->stop();
 });
 
-// docker-compose run phpswoole php /var/www/html/server/coredis_test.php
+//docker-compose run phpswoole php /var/www/html/server/coredis.php
 
 
 

+ 1 - 1
test/TestRefillThird.php

@@ -94,7 +94,7 @@ class TestRefillThird extends TestCase
     public function testPushPhones()
     {
         $time = time();
-        for ($i = 0; $i < 1000000; $i++)
+        for ($i = 0; $i < 1000; $i++)
         {
             $params = [ 'mchid' => 1092,
                 'buyer_id' => 60221,

+ 8 - 0
test/examples/atomic/long.php

@@ -0,0 +1,8 @@
+<?php
+$l = new Swoole\Atomic\Long( -2 ** 36);
+echo $l->get()."\n";
+echo $l->add(20)."\n";
+echo $l->sub(20)."\n";
+echo $l->sub(-20)."\n";
+echo $l->cmpset(-2 ** 36, 0)."\n";
+echo $l->cmpset(-2 ** 36 + 20, 0)."\n";

+ 7 - 0
test/examples/atomic/test.php

@@ -0,0 +1,7 @@
+<?php
+$atomic = new swoole_atomic(123);
+echo $atomic->add(12)."\n";
+echo $atomic->sub(11)."\n";
+echo $atomic->cmpset(122, 999)."\n";
+echo $atomic->cmpset(124, 999)."\n";
+echo $atomic->get()."\n";

+ 16 - 0
test/examples/atomic/wait.php

@@ -0,0 +1,16 @@
+<?php
+$n = new swoole_atomic(0);
+
+if (pcntl_fork() > 0)
+{
+	echo "master start\n";
+	$n->wait(1.5);
+	echo "master end\n";
+}
+else
+{
+	echo "child start\n";
+	sleep(1);
+	$n->wakeup();
+	echo "child end\n";
+}

+ 28 - 0
test/examples/c10k.php

@@ -0,0 +1,28 @@
+<?php
+$clients = array();
+for($j = 0; $j < 2; $j++)
+{
+	$pid = pcntl_fork();
+	if($pid > 0)
+	{
+		continue;
+	}
+	else
+	{
+		for($i = 0; $i < 9999; $i++){
+			$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC); //同步阻塞
+			$ret = $client->connect('127.0.0.1', 9501, 0.5);
+			if(!$ret)
+			{
+				echo "#$i\tConnect fail.  errno=".$client->errCode;
+				die("\n");
+			}
+			$clients[] = $client;
+			usleep(10);
+		}
+		echo "Worker #".posix_getpid()." connect $i finish\n";
+		sleep(1000);
+		exit;
+	}
+}
+sleep(1000);

+ 53 - 0
test/examples/client/async.php

@@ -0,0 +1,53 @@
+<?php
+$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞
+//$client->set(array(
+//    'socket_buffer_size' => 1024 * 1024 * 2,
+//    'open_eof_check' => true,
+//    'package_eof' => "\r\n\r\n",
+//));
+
+$client->_count = 0;
+$client->on("connect", function(swoole_client $cli) {
+    //swoole_timer_clear($cli->timer);
+    $cli->send("GET / HTTP/1.1\r\n\r\n");
+    //$cli->sendfile(__DIR__.'/test.txt');
+    //$cli->_count = 0;
+});
+
+$client->on("receive", function(swoole_client $cli, $data){
+    echo "Receive: $data";
+    $cli->_count++;
+    if ($cli->_count > 5)
+    {
+        //睡眠模式,不再接收新的数据
+        echo "count=10, sleep(5000ms)\n";
+        $cli->sleep();
+        $cli->_count = 0;
+        swoole_timer_after(5000, function() use ($cli) {
+            //唤醒
+            $cli->wakeup();
+        });
+        //$cli->close();
+        return;
+    }
+    else
+    {
+        $cli->send(str_repeat('A', 100)."\n");
+    }
+});
+
+$client->on("error", function(swoole_client $cli){
+    echo "error\n";
+});
+
+$client->on("close", function(swoole_client $cli){
+    echo "Connection close\n";
+});
+
+$client->connect('127.0.0.1', 9501);
+//$client->timer = swoole_timer_after(1000, function () use ($client) {
+//    echo "socket timeout\n";
+//    $client->close();
+//});
+
+//echo "connect to 127.0.0.1:9501\n";

+ 33 - 0
test/examples/client/get_socket.php

@@ -0,0 +1,33 @@
+<?php
+
+function getClient()
+{
+    $client = new swoole_client(SWOOLE_SOCK_TCP);
+    if (!$client->connect('127.0.0.1', 9501, -1))
+    {
+        exit("connect failed. Error: {$client->errCode}\n");
+    }
+
+    $res = $client->getSocket();
+    return $client;
+}
+
+$client = getClient();
+
+$count = 0;
+//$client->set(array('open_eof_check' => true, 'package_eof' => "\r\n\r\n"));
+
+//$client = new swoole_client(SWOOLE_SOCK_UNIX_DGRAM, SWOOLE_SOCK_SYNC); //同步阻塞
+//if (!$client->connect(dirname(__DIR__).'/server/svr.sock', 0, -1, 1))
+
+
+var_dump($client->getsockname());
+$client->send("hello world\r\n\r\n");
+
+//for($i=0; $i < 3; $i ++)
+{
+    echo $client->recv();
+    sleep(1);
+}
+
+$client->close();

+ 18 - 0
test/examples/client/long_tcp.php

@@ -0,0 +1,18 @@
+<?php
+for($i=0; $i < 100; $i++)
+{
+	$client = new swoole_client(SWOOLE_TCP | SWOOLE_KEEP);
+	if(!$client->connect('127.0.0.1', 9501))
+	{
+		exit("connect failed\n");
+	}
+	$client->send(str_repeat("A", 600));
+	$data = $client->recv(7000, 0);
+	if($data === false)
+	{
+		echo "recv fail\n";
+		break;
+	}
+	var_dump($data);
+	$client->close();
+}

+ 32 - 0
test/examples/client/select.php

@@ -0,0 +1,32 @@
+<?php
+$clients = array();
+
+for($i=0; $i< 20; $i++)
+{
+    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC); //同步阻塞
+    $ret = $client->connect('127.0.0.1', 9501, 0.5, 0);
+    if(!$ret)
+    {
+        echo "Connect Server fail.errCode=".$client->errCode;
+    }
+    else
+    {
+    	$client->send("HELLO WORLD\n");
+    	$clients[$client->sock] = $client;
+    }
+}
+
+while (!empty($clients))
+{
+    $write = $error = array();
+    $read = array_values($clients);
+    $n = swoole_client_select($read, $write, $error, 0.6);
+    if ($n > 0)
+    {
+        foreach ($read as $index => $c)
+        {
+            echo "Recv #{$c->sock}: " . $c->recv() . "\n";
+            unset($clients[$c->sock]);
+        }
+    }
+}

+ 29 - 0
test/examples/client/sync.php

@@ -0,0 +1,29 @@
+<?php
+$client = new swoole_client(SWOOLE_SOCK_TCP);
+$count = 0;
+//$client->set(array('open_eof_check' => true, 'package_eof' => "\r\n\r\n"));
+
+//$client = new swoole_client(SWOOLE_SOCK_UNIX_DGRAM, SWOOLE_SOCK_SYNC); //同步阻塞
+//if (!$client->connect(dirname(__DIR__).'/server/svr.sock', 0, -1, 1))
+
+do_connect:
+if (!$client->connect('127.0.0.1', 9501, -1))
+{
+    exit("connect failed. Error: {$client->errCode}\n");
+}
+
+var_dump($client->getsockname());
+$client->send("hello world\r\n\r\n");
+
+//for($i=0; $i < 3; $i ++)
+{
+    echo $client->recv();
+    sleep(1);
+}
+
+$client->close();
+$count++;
+if ($count < 20)
+{
+    goto do_connect;
+}

+ 9 - 0
test/examples/client/test.txt

@@ -0,0 +1,9 @@
+XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx
+XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXx
+XXXXXXXXXXXXXXXXXXXXXXx
+XXXXXXXXXXXXXXXXXXXXX
+XXXXXXXXXXXXXXXXXXXXXXX
+AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
+BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB
+TTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTTT
+DDDDDDDDDDDDDDDDDDDDDDDDDDD

+ 23 - 0
test/examples/client/udp_async.php

@@ -0,0 +1,23 @@
+<?php
+$client = new swoole_client(SWOOLE_SOCK_UDP, SWOOLE_SOCK_ASYNC); //异步非阻塞
+
+$client->on("connect", function(swoole_client $cli) {
+    echo "connected\n";
+    $cli->send("hello world\n");
+});
+
+$client->on('close', function($cli){
+    echo "closed\n";
+});
+
+$client->on('error', function($cli){
+    echo "error\n";
+});
+
+$client->on("receive", function(swoole_client $cli, $data){
+	echo "received: $data\n";
+	sleep(1);
+	$cli->send("hello_".rand(1000,9999));
+});
+
+$client->connect('127.0.0.1', 9502, 0.5);

+ 10 - 0
test/examples/client/udp_sync.php

@@ -0,0 +1,10 @@
+<?php
+$client = new swoole_client(SWOOLE_SOCK_UDP, SWOOLE_SOCK_SYNC);
+$client->connect('127.0.0.1', 9502);
+
+for ($i = 0; $i < 100; $i++)
+{
+    $client->send("admin");
+    echo $client->recv()."\n";
+    sleep(1);
+}

+ 21 - 0
test/examples/client2.php

@@ -0,0 +1,21 @@
+<?php
+$clients = array();
+for($i = 0; $i < 1; $i++){
+    $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC); //同步阻塞
+    $ret = $client->connect('127.0.0.1', 9501, 0.5, 0);
+    if(!$ret)
+    {
+        echo "Over flow. errno=".$client->errCode;
+        die("\n");
+    }
+    $clients[] = $client;
+}
+sleep(1);
+while (1) {
+    foreach ($clients as $client) {
+        $client->send("sss");
+        $data = $client->recv();
+        var_dump($data);
+    }
+    sleep(1);
+}

+ 117 - 0
test/examples/coroutine/TestHttpServ.php

@@ -0,0 +1,117 @@
+<?php
+/**
+ * @Author: winterswang
+ * @Date:   2015-06-18 16:45:09
+ * @Last Modified by:   winterswang
+ * @Last Modified time: 2016-09-18 17:33:51
+ */
+
+class TestHttpServer {
+
+	public $http;
+	public $queue;
+	public $setting = array();
+
+	/**
+	 * [__construct description]
+	 * @param array $setting [description]
+	 */
+	public function __construct(){
+
+	}
+
+	public function set($setting){
+
+		$this ->setting = $setting;
+	}
+
+	/**
+	 * [init description]
+	 * @return [type] [description]
+	 */
+	public function init(){
+
+		if (!isset($this ->setting['host'])) {
+			$this ->setting['host'] = '0.0.0.0';
+		}
+		if (!isset($this ->setting['port'])) {
+			$this ->setting['port'] = '9999';
+		}
+
+		$this ->http = new swoole_http_server($this ->setting['host'], $this ->setting['port']);
+		$this ->http ->set($this ->setting);
+
+		$this ->http ->on('request', array($this, 'onRequest'));
+		$this ->http ->on('close', array($this, 'onClose'));
+	}
+
+	/**
+	 * [onRequest description]
+	 * @param  [type] $request  [description]
+	 * @param  [type] $response [description]
+	 * @return [type]           [description]
+	 */
+	public function onRequest($request, $response){
+
+		// $udp = new swoole_client(SWOOLE_SOCK_UDP, SWOOLE_SOCK_ASYNC);
+		// $udp->on("connect", function(swoole_client $cli) {
+		//     $cli->send("udp test");
+		// });
+		// $udp->on("receive", function(swoole_client $cli, $data)use($response){
+
+			$tcp = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
+			$tcp->on("connect", function(swoole_client $cli) {
+			    $cli->send("tcp test");
+			});
+			$tcp->on("receive", function(swoole_client $cli, $data)use($response){
+				$response ->end("<h1> swoole response</h1>");
+			});
+			$tcp->on("close", function(swoole_client $cli){
+			});
+			$tcp->on("error", function(swoole_client $cli){
+			});
+			$tcp->connect('10.100.64.151', 9805);
+
+		// });
+		// $udp->on("close", function(swoole_client $cli){
+		// });
+		// $udp->connect('10.100.65.222', 9906);
+
+	}
+
+	/**
+	 * [onClose description]
+	 * @param  [type] $server  [description]
+	 * @param  [type] $fd      [description]
+	 * @param  [type] $reactor_id [description]
+	 * @return [type]          [description]
+	 */
+	public function onClose($server, $fd, $reactor_id){
+
+		//echo " on close fd = $fd reactor_id = $reactor_id \n";
+	}
+
+	/**
+	 * [start description]
+	 * @return [type] [description]
+	 */
+	public function start(){
+
+		$this ->init();
+		$this ->http ->start();
+	}
+}
+
+$setting = array(
+		'host' => '0.0.0.0',
+		'port' => 10005,
+		'worker_num' => 4,
+		'dispatch_mode' => 2,   //固定分配请求到worker
+		'reactor_num' => 4,     //亲核
+		'daemonize' => 1,       //守护进程
+		'backlog' => 128,
+		'log_file' => '/data/log/test_http_server.log',
+);
+$th = new TestHttpServer();
+$th ->set($setting);
+$th ->start();

+ 59 - 0
test/examples/coroutine/backtrace.php

@@ -0,0 +1,59 @@
+<?php
+function test1() {
+    test2();
+}
+
+function test2() {
+    while(true) {
+        co::sleep(10);
+        echo __FUNCTION__." \n";
+    }
+}
+
+$cid = go(function () {
+    test1();
+});
+
+go(function () use ($cid) {
+    while(true) {
+        echo "BackTrace[$cid]:\n-----------------------------------------------\n";
+        echo get_debug_print_backtrace(co::getBackTrace($cid))."\n";
+        co::sleep(3);
+    }
+});
+
+function get_debug_print_backtrace($traces){
+    $ret = array();
+    foreach($traces as $i => $call){
+        $object = '';
+        if (isset($call['class'])) {
+            $object = $call['class'].$call['type'];
+            if (is_array($call['args'])) {
+                foreach ($call['args'] as &$arg) {
+                    get_arg($arg);
+                }
+            }
+        }
+
+        $ret[] = '#'.str_pad($i - $traces_to_ignore, 3, ' ')
+        .$object.$call['function'].'('.implode(', ', $call['args'])
+        .') called at ['.$call['file'].':'.$call['line'].']';
+    }
+
+    return implode("\n",$ret);
+}
+
+function get_arg(&$arg) {
+    if (is_object($arg)) {
+        $arr = (array)$arg;
+        $args = array();
+        foreach($arr as $key => $value) {
+            if (strpos($key, chr(0)) !== false) {
+                $key = '';    // Private variable found
+            }
+            $args[] =  '['.$key.'] => '.get_arg($value);
+        }
+
+        $arg = get_class($arg) . ' Object ('.implode(',', $args).')';
+    }
+}

+ 25 - 0
test/examples/coroutine/before_server_start.php

@@ -0,0 +1,25 @@
+<?php
+go(function ()
+{
+    co::sleep(1);
+
+    $http = new swoole_http_server("127.0.0.1", 9501, SWOOLE_BASE);
+
+    $http->on("start", function ($server)
+    {
+        echo "Swoole http server is started at http://127.0.0.1:9501\n";
+    });
+
+    $http->on("request", function ($request, $response)
+    {
+        var_dump($request->header);
+        var_dump($request->server);
+
+        $response->header("Content-Type", "text/plain");
+        $response->status(200);
+        $response->end("test");
+    });
+    echo "start\n";
+    $http->start();
+    echo "end\n";
+});

+ 18 - 0
test/examples/coroutine/behavior/do-while.php

@@ -0,0 +1,18 @@
+<?php
+Swoole\Coroutine::set([
+    'max_death_ms' => 2000,
+    'death_loop_threshold' => 5,
+]);
+echo "start\n";
+go(function () {
+    echo "coro start\n";
+    do{
+        echo "111\n";
+        sleep(1);
+    } while(1);
+});
+
+go(function () {
+    echo "222222\n";
+});
+echo "end\n";

+ 27 - 0
test/examples/coroutine/behavior/for.php

@@ -0,0 +1,27 @@
+<?php
+co::set(['enable_preemptive_scheduler' => true]);
+$start = microtime(1);
+echo "start\n";
+$flag = 1;
+
+go(function () use (&$flag) {    
+    echo "coro 1 start to loop\n";
+    $i = 0;
+    for (;;) {
+//         echo "$i\n";
+        if (!$flag) {
+            break;
+        }
+        $i++;
+    }
+    echo "coro 1 can exit\n";
+});
+    
+$end = microtime(1);
+$msec = ($end - $start) * 1000;
+echo "use time $msec\n";
+go(function () use (&$flag) {
+    echo "coro 2 set flag = false\n";
+    $flag = false;
+});
+echo "end\n";

+ 14 - 0
test/examples/coroutine/behavior/foreach.php

@@ -0,0 +1,14 @@
+<?php
+echo "start\n";
+go(function () {
+    echo "coro start\n";
+    $arr = range(0, 20);
+    foreach($arr as $k=>$v){
+        echo $v."\n";
+    }
+});
+
+go(function () {
+    echo "222222\n";
+});
+echo "end\n";

+ 14 - 0
test/examples/coroutine/behavior/goto.php

@@ -0,0 +1,14 @@
+<?php
+echo "start\n";
+go(function () {
+    echo "coro start\n";
+    loop:
+    echo "111\n";
+    sleep(1);
+    goto loop;
+});
+
+go(function () {
+    echo "222222\n";
+});
+echo "end\n";

+ 24 - 0
test/examples/coroutine/behavior/preemptive_timer.php

@@ -0,0 +1,24 @@
+<?php
+co::set(['enable_preemptive_scheduler' => true]);
+go(function (){
+    $exit = false;
+    while (true){
+        $res = Swoole\Coroutine::stats();
+        $num = $res['coroutine_num'];
+        if ($num < 10){
+            go(function () use(&$exit){
+                echo "cid:".Swoole\Coroutine::getCid()." start\n";
+                Swoole\Coroutine::sleep(1);
+                echo "cid ".Swoole\Coroutine::getCid()." end\n";
+                $exit = true;
+            });
+        }
+        if ($exit) {
+            echo "cid ".Swoole\Coroutine::getCid()." break\n";
+            break;
+        }
+    }
+    echo "cid ".Swoole\Coroutine::getCid()." exit\n";
+});
+echo "main end\n";
+

+ 32 - 0
test/examples/coroutine/behavior/tick.php

@@ -0,0 +1,32 @@
+<?php
+declare(ticks=10);
+
+$max_msec = 10;
+Swoole\Coroutine::set([
+    'max_exec_msec' => $max_msec,
+]);
+
+$s = microtime(1);
+echo "start\n";
+$flag = 1;
+go(function () use (&$flag, $max_msec, $s){
+    echo "coro 1 start to loop for $max_msec msec\n";
+    $n = 10000000;
+    $i = 0;
+    while($n--) {
+        $i ++;
+    }
+    echo "coro 1 can exit\n";
+    $t = microtime(1);
+    $u = $t-$s;
+    echo "coro 1 use time ".(($t-$s) * 1000)." ms\n";
+});
+
+$t = microtime(1);
+$u = $t-$s;
+echo "shedule use time ".($u * 1000)." ms\n";
+go(function () use (&$flag){
+    echo "coro 2 set flag = false\n";
+    $flag = false;
+});
+echo "end\n";

+ 35 - 0
test/examples/coroutine/behavior/while.php

@@ -0,0 +1,35 @@
+<?php
+Swoole\Coroutine::set([
+    'max_death_ms' => 5000,
+]);
+$s = microtime(1);
+echo "start\n";
+go(function () {
+    echo "coro 1  start\n";
+    $x = 5;
+    $i = 0;
+    while(!0) {
+        $i ++;
+        echo "coro 1 $i\n";
+        sleep(1);
+    }
+});
+
+go(function () {
+    echo "coro 2  start\n";
+    $x = 5;
+    $i = 0;
+    while(1) {
+        $i ++;
+        echo "coro 2 $i\n";
+        sleep(1);
+    }
+});
+
+$t = microtime(1);
+$u = $t-$s;
+echo "use time $u s\n";
+go(function () {
+    echo "----------------------\n";
+});
+echo "end\n";

+ 27 - 0
test/examples/coroutine/behavior/while2.php

@@ -0,0 +1,27 @@
+<?php
+Swoole\Coroutine::set([
+    'max_death_ms' => 5000,
+]);
+$s = microtime(1);
+echo "start\n";
+
+$flag = 1;
+go(function () use (&$flag){
+    echo "coro 1 start\n";
+    $i = 0;
+    while($flag) {
+        $i ++;
+        echo "$i\n";
+        sleep(1);
+    }
+    echo "coro 1 can exit\n";
+});
+
+$t = microtime(1);
+$u = $t-$s;
+echo "use time $u s\n";
+go(function () use (&$flag){
+    echo " coro 2 set flag = false\n";
+    $flag = false;
+});
+echo "end\n";

+ 32 - 0
test/examples/coroutine/channel/test.php

@@ -0,0 +1,32 @@
+<?php
+function BatchExecMethodByCo()
+{
+    $args = func_get_args();
+    $channel = new \Swoole\Coroutine\Channel(count($args));
+    foreach ($args as $key => $func) {
+        go(function()use($channel,$func,$key){
+            $res = $func();
+            $channel->push([$key=>$res]);
+        });
+    }
+    $list = [];
+    go(function()use(&$list,$args,$channel){
+        foreach ($args as $key => $chan) {
+            $list[$key] = $channel->pop();
+        }
+    });
+    swoole_event_wait();
+    return $list;
+}
+function test($value='')
+{
+    \Co::sleep(1);
+    return "test\n";
+}
+function test2($value='')
+{
+    \Co::sleep(1);
+    return "test2 ".rand(1,10)."\n";
+}
+$r = BatchExecMethodByCo("test","test2","test");
+var_dump($r);

+ 27 - 0
test/examples/coroutine/client_send_yield.php

@@ -0,0 +1,27 @@
+<?php
+go(function () {
+    $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+    $client->set(array(
+        'socket_buffer_size' => 1024 * 512,
+    ));
+    if (!$client->connect('127.0.0.1', 9501, -1))
+    {
+        exit("connect failed. Error: {$client->errCode}\n");
+    }
+    $length = 0;
+    $size = 1024 * 64;
+    while (true)
+    {
+        $ret = $client->send(str_repeat('A', $size));
+        if ($ret == false)
+        {
+            var_dump($ret);
+            break;
+        }
+        $length += $size;
+        echo "send $length success\n";
+    }
+    var_dump($client->errCode);
+});
+
+swoole_event_wait();

+ 27 - 0
test/examples/coroutine/client_send_yield_server.php

@@ -0,0 +1,27 @@
+<?php
+$socket = stream_socket_server("tcp://0.0.0.0:9501", $errno, $errstr);
+if (!$socket) {
+    echo "$errstr ($errno)<br />\n";
+} else {
+    while (true) {
+        $conn = stream_socket_accept($socket);
+        if (!$conn) {
+            continue;
+        }
+        $i = 0;
+        $length = 0;
+        while(true) {
+            $data = fread($conn, 8192);
+            if ($data == false)
+            {
+                break;
+            }
+            $length += strlen($data);
+            echo "recv " . $length . " bytes\n";
+            usleep(100000);
+        }
+        fclose($conn);
+        echo "closed\n";
+    }
+    fclose($socket);
+}

+ 19 - 0
test/examples/coroutine/coro_array_map.php

@@ -0,0 +1,19 @@
+<?php
+
+use Swoole\Coroutine as co;
+
+co::create(function() {
+    array_map("test",array("func param\n"));
+    echo "co flow end\n";
+});
+
+function test($p) {
+    go(function() use ($p){
+        echo $p;
+        $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+        $res = $client->connect('127.0.0.1', 9501, 1);
+        echo "co resume : connect ret = ".var_export($res,1)."\n";
+        echo "map func end \n";
+    });
+}
+echo "main end\n";

+ 19 - 0
test/examples/coroutine/coro_call_user.php

@@ -0,0 +1,19 @@
+<?php
+use Swoole\Coroutine as co;
+co::set(['trace_flags' => 1]);
+
+co::create(function() {
+    echo "co func start\n";
+    $name = "call_user_func";
+    $ret = $name("test","test\n");
+	echo "co func end ret:{$ret}\n";
+});
+
+function test($params)
+{
+    echo "func params:$params";
+    co::sleep(1);
+    echo "func end\n";
+    return "test return\n";
+}
+echo "main script last\n";

+ 25 - 0
test/examples/coroutine/coro_channel.php

@@ -0,0 +1,25 @@
+<?php
+$http = new swoole_http_server("127.0.0.1", 9501, SWOOLE_BASE);
+$http->set(array(
+    'log_file' => '/dev/null'
+));
+use Swoole\Coroutine as co;
+// $http->on("WorkerStart", function (\swoole_server $serv)
+// {
+//
+// });
+$http->on('request', function (swoole_http_request $request, swoole_http_response $response)
+{
+    $ch = new co\Channel(1);
+    $out = new co\Channel(1);
+    Swoole\Coroutine::create(function() use ($ch, $out) {
+        $out->push("OK");
+        $out->push("OK");
+    });
+    $ret = $out->pop();
+    var_dump($ret);
+    $ret = $out->pop();
+    var_dump($ret);
+    $response->end("$ret\n");
+});
+$http->start();

+ 28 - 0
test/examples/coroutine/coro_destruct.php

@@ -0,0 +1,28 @@
+<?php
+use Swoole\Coroutine as co;
+class T
+{
+    function __construct()
+    {
+
+    }
+
+    function test()
+    {
+        echo "call function \n";
+    }
+
+    function __destruct()
+    {
+        go(function () {
+            echo "coro start\n";
+            co::sleep(1.0);
+            echo "coro exit\n";
+        });
+        echo "111\n";
+    }
+}
+
+$t = new T();
+$t->test();
+echo "end \n";

+ 32 - 0
test/examples/coroutine/coro_destuct.php

@@ -0,0 +1,32 @@
+<?php
+require __DIR__ . "/coro_include.php";
+
+class T
+{
+    function __construct()
+    {
+        echo "call __construct \n";
+    }
+
+      function test()
+      {
+        echo "call function \n";
+      }
+
+      function __destruct()
+      {
+        echo "call __destruct \n";
+        go(function () {
+            echo "co[1] start\n";
+            $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+            $res = $client->connect('127.0.0.1', 9501, 1);
+            co::sleep(1.0);
+            echo "co[1] resume : connect ret = ".var_export($res,1)."\n";
+            echo "co[1] exit\n";
+        });
+      }
+}
+
+$t = new T();
+$t->test();
+unset($t);

+ 7 - 0
test/examples/coroutine/coro_empty.php

@@ -0,0 +1,7 @@
+<?php
+// co::set(['trace_flags' => 1]);
+
+co::create(function () {
+    echo "no coro exit\n";
+});
+echo "exec file end\n";

+ 11 - 0
test/examples/coroutine/coro_gethost.php

@@ -0,0 +1,11 @@
+<?php
+require __DIR__ . "/coro_include.php";
+use Swoole\Coroutine as co;
+
+co::create(function () {
+    $ip = co::gethostbyname('www.baidu.com');
+    var_dump($ip);
+});
+echo "111\n";
+
+echo "222\n";

+ 9 - 0
test/examples/coroutine/coro_include.php

@@ -0,0 +1,9 @@
+<?php
+if (substr(PHP_OS, 0, 3) == 'WIN')
+{
+    exit("skip for Windows");
+}
+if (!extension_loaded("swoole"))
+{
+    exit("swoole extension is required");
+}

+ 22 - 0
test/examples/coroutine/coro_invoke.php

@@ -0,0 +1,22 @@
+<?php
+use Swoole\Coroutine as co;
+co::set(['trace_flags' => 1]);
+
+co::create(function() {
+
+
+    $function = new ReflectionFunction('title');
+
+    $function->invoke();
+    echo "invoke444\n";
+
+});
+
+function title() {
+    echo "333invoke_________________________________\n";
+    $tcpclient = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+    var_dump($tcpclient->connect('127.0.0.1', 9501, 1));
+
+}
+
+echo "111\n";

+ 17 - 0
test/examples/coroutine/coro_nested.php

@@ -0,0 +1,17 @@
+<?php
+require __DIR__ . "/coro_include.php";
+echo "before coro\n";
+go(function () {
+    echo "co[1] start\n";
+
+    $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+    $res = $client->connect('127.0.0.1', 9501, 1);
+    echo "co[1] connect ret = ".var_export($res,1)."\n";
+    co::sleep(1);
+    $res = $client->send("hello world\n");
+    echo "co[1] send ret = ".var_export($res,1)."\n";
+    $res =  $client->recv();
+    echo "co[1] recv ret = ".var_export($res,1)."\n";
+    echo "co[1] exit\n";
+});
+echo "out coro \n";

+ 16 - 0
test/examples/coroutine/coro_nested_empty.php

@@ -0,0 +1,16 @@
+<?php
+require __DIR__ . "/coro_include.php";
+function test()
+{
+    echo "before coro\n";
+    go(function () {
+        echo "co[1] start\n";
+        go(function () {
+            echo "co[2] start\n";
+            echo "co[2] exit\n";
+        });
+        echo "co[1] exit\n";
+    });
+    echo "func end \n";
+}
+test();

+ 39 - 0
test/examples/coroutine/coro_serialize.php

@@ -0,0 +1,39 @@
+<?php
+use Swoole\Coroutine as co;
+class Obj {
+  public $a;
+  protected $b;
+  private $c;
+  var $d;
+
+  function __construct($a, $b, $c, $d) {
+    $this->a = $a;
+    $this->b = $b;
+    $this->c = $c;
+    $this->d = $d;
+  }
+
+  function __sleep() {
+      // co::sleep(0.5);
+	$client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+	$res = $client->connect('127.0.0.1', 9501, 10);
+    var_dump($res);
+	if ($res)
+	{
+	    echo("connect success. Error: {$client->errCode}\n");
+	}
+    echo "sleep\n";
+    return array('a', 'b', 'c');
+  }
+
+    // function __wakeup() {
+    //    $this->d = $this->a + $this->b + $this->c;
+    // }
+}
+$o = new Obj(1, 2, 3, 4);
+co::create(function() use($o) {
+    $serialized = serialize($o);
+    $unserialized = unserialize($serialized);
+    echo "res:".var_export($unserialized,1)."\n";
+    echo "call user\n";
+});

+ 10 - 0
test/examples/coroutine/coro_set_stack_size.php

@@ -0,0 +1,10 @@
+<?php
+use Swoole\Coroutine as co;
+
+co::set(['stack_size' => 1024*1024*4]);
+
+co::create(function () {
+    var_dump(co::stats());
+    echo "no coro exit\n";
+});
+echo "exec file end\n";

+ 9 - 0
test/examples/coroutine/coro_sleep.php

@@ -0,0 +1,9 @@
+<?php
+// require  __DIR__ . "/coro_include.php";
+use Swoole\Coroutine as co;
+co::create(function () {
+    echo "start\n";
+    co::sleep(0.5);
+    echo "OK\n";
+});
+echo "11\n";

+ 19 - 0
test/examples/coroutine/coro_stackless.php

@@ -0,0 +1,19 @@
+<?php
+require __DIR__ . "/coro_include.php";
+use Swoole\Coroutine as co;
+
+echo "start\n";
+co::create(function () {
+    $client = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+    $res = $client->connect('127.0.0.1', 9501, 1);
+    var_dump($res);
+    if ($res) {
+        echo ("connect success. Error: {$client->errCode}\n");
+    }
+
+    $res = $client->send("hello");
+    echo "send res:" . var_export($res, 1) . "\n";
+    $data = $client->recv();
+    echo "recv data" . var_export($data, 1) . "\n";
+});
+echo "end\n";

+ 16 - 0
test/examples/coroutine/coro_util.php

@@ -0,0 +1,16 @@
+<?php
+use Swoole\Coroutine as co;
+
+$id = go(function(){
+    $id = co::getUid();
+    echo "start coro $id\n";
+    co::suspend($id);
+    echo "resume coro $id @1\n";
+    co::suspend($id);
+    echo "resume coro $id @2\n";
+});
+echo "start to resume $id @1\n";
+co::resume($id);
+echo "start to resume $id @2\n";
+co::resume($id);
+echo "main\n";

+ 40 - 0
test/examples/coroutine/csp.php

@@ -0,0 +1,40 @@
+<?php
+$serv = new \swoole_http_server("127.0.0.1", 9503, SWOOLE_BASE);
+
+$serv->on('request', function ($req, $resp) {
+    $chan = new chan(2);
+    go(function () use ($chan) {
+        $cli = new Swoole\Coroutine\Http\Client('www.baidu.com', 443, true);
+            $cli->set(['timeout' => 10]);
+            $cli->setHeaders([
+            'Host' => "www.baidu.com",
+            "User-Agent" => 'Chrome/49.0.2587.3',
+            'Accept' => 'text/html,application/xhtml+xml,application/xml',
+            'Accept-Encoding' => 'gzip',
+        ]);
+        $ret = $cli->get('/');
+        $chan->push(['www.baidu.com' => substr(trim(strip_tags($cli->body)), 0, 100)]);
+    });
+
+    go(function () use ($chan) {
+        $cli = new Swoole\Coroutine\Http\Client('www.taobao.com', 443, true);
+        $cli->set(['timeout' => 10]);
+        $cli->setHeaders([
+            'Host' => "www.taobao.com",
+            "User-Agent" => 'Chrome/49.0.2587.3',
+            'Accept' => 'text/html,application/xhtml+xml,application/xml',
+            'Accept-Encoding' => 'gzip',
+        ]);
+        $ret = $cli->get('/');
+        $chan->push(['www.taobao.com' => substr(trim(strip_tags($cli->body)), 0, 100)]);
+    });
+
+    $result = [];
+    for ($i = 0; $i < 2; $i++)
+    {
+        $result += $chan->pop();
+    }
+    $resp->header('Content-Type', 'text/html;charset=utf-8');
+    $resp->end(var_export($result, true));
+});
+$serv->start();

+ 11 - 0
test/examples/coroutine/deadlock.php

@@ -0,0 +1,11 @@
+<?php
+$lock = new Swoole\Lock();
+$c = 2;
+
+while ($c--) {
+    go(function () use ($lock) {
+        $lock->lock();
+        Co::sleep(1);
+        $lock->unlock();
+    });
+}

+ 27 - 0
test/examples/coroutine/defer.php

@@ -0,0 +1,27 @@
+<?php
+go(function () {
+
+    defer(function () {
+        co::sleep(1);
+        echo "end 2\n";
+
+        defer(function () {
+            co::sleep(1);
+            echo "end 3\n";
+        });
+
+        defer(function () {
+            co::sleep(1);
+            echo "end 5\n";
+        });
+    });
+
+    defer(function () {
+        co::sleep(1);
+        echo "end 4\n";
+    });
+
+    echo "begin\n";
+    co::sleep(1);
+    echo "end 1\n";
+});

+ 79 - 0
test/examples/coroutine/defer_client.php

@@ -0,0 +1,79 @@
+<?php
+/* new multi implement test */
+$server = new Swoole\Http\Server("127.0.0.1", 9502, SWOOLE_BASE);
+
+$server->set([
+	'worker_num' => 1,
+]);
+
+$server->on('Request', function ($request, $response) {
+	$redis = new Swoole\Coroutine\Redis();
+	$res = $redis->connect('127.0.0.1', 6379);
+	if ($res == false) {
+		$response->end("Redis connect fail!");
+		return;
+	}
+	$redis->setDefer(true);
+	$redis->get('key');
+	$res = $redis->get('key');//get false
+	var_dump($res);
+
+	var_dump($redis->setDefer());//get true
+	var_dump($redis->setDefer(false));//get false
+
+	//穿插其他client也能正常工作
+	$redis_tmp = new Swoole\Coroutine\Redis();
+	$res = $redis_tmp->connect('127.0.0.1', 6379);
+	if ($res == false) {
+		$response->end("Redis connect fail!");
+		return;
+	}
+	$res = $redis_tmp->set('key_tmp', 'HaHa');//get true
+	var_dump($res);
+
+
+	$http_client= new Swoole\Coroutine\Http\Client('km.oa.com', 80);
+	$http_client->setDefer();
+	$http_client->get('/');
+
+	$mysql = new Swoole\Coroutine\MySQL();
+	$res = $mysql->connect(['host' => '192.168.244.128', 'user' => 'mha_manager', 'password' => 'mhapass', 'database' => 'tt']);
+	if ($res == false) {
+		$response->end("MySQL connect fail!");
+		return;
+	}
+	$mysql->setDefer(true);
+	$mysql->query('select sleep(1)', 2);
+
+	$udp = new Swoole\Coroutine\Client(SWOOLE_SOCK_UDP);
+    $res = $udp->connect("127.0.0.1", 9906, 2);
+	$udp->send('Hello World!');
+
+	//穿插其他client也能正常工作
+	$udp_tmp = new Swoole\Coroutine\Client(SWOOLE_SOCK_UDP);
+    $res = $udp_tmp->connect("127.0.0.1", 9909, 2);//nonexistent server
+	$res = $udp_tmp->recv();//get false with timeout
+	var_dump($res);
+
+	$udp_res = $udp->recv();
+	$res = $mysql->query('select sleep(1)', 2);//get false
+	var_dump($res);
+	$res = $mysql->setDefer(false);
+	var_dump($res);//get false
+	$res = $mysql->setDefer();
+	var_dump($res);//get true
+	$mysql_res = $mysql->recv();
+	$res = $redis->get('key');//get false
+	var_dump($res);
+	$redis_res = $redis->recv();
+	$res = $http_client->get('/');
+	var_dump($res);//get false
+	$res = $http_client->recv();
+	var_dump($res);//get true
+
+	var_dump($udp_res, $mysql_res, $redis_res, $http_client);
+	var_dump($http_client->setDefer(false));
+	var_dump($mysql->getDefer(), $redis->getDefer(), $http_client->getDefer());
+	$response->end('Test End');
+});
+$server->start();

+ 27 - 0
test/examples/coroutine/enable_coroutine.php

@@ -0,0 +1,27 @@
+<?php
+
+use Swoole\Http\Request;
+use Swoole\Http\Response;
+
+$http = new swoole_http_server('127.0.0.1', 9501);
+
+$http->set([
+    'enable_coroutine' => false, // close build-in coroutine
+]);
+
+$http->on('workerStart', function () {
+    echo "Coroutine is " . (Co::getuid() > 0 ? 'enable' : 'disable')."\n";
+});
+
+$http->on("request", function (Request $request, Response $response) {
+    $response->header("Content-Type", "text/plain");
+    if ($request->server['request_uri'] == '/co') {
+        go(function () use ($response) {
+            $response->end("Hello Coroutine #" . Co::getuid());
+        });
+    } else {
+        $response->end("Hello Swoole #" . Co::getuid());
+    }
+});
+
+$http->start();

+ 14 - 0
test/examples/coroutine/exception/empty.php

@@ -0,0 +1,14 @@
+<?php
+go(function () {
+    try {
+        echo "before\n";
+        co::sleep(0.5);
+        echo "after\n";
+        throw new Exception('coro Exception.');
+    } catch (Exception $e) {
+        echo 'Caught exception: ',  $e->getMessage(), "\n";
+    } finally {
+        echo "First finally.\n";
+    }
+});
+echo "exec file end\n";

+ 5 - 0
test/examples/coroutine/exec.php

@@ -0,0 +1,5 @@
+<?php
+go(function () {
+
+	var_dump(co::exec("ls /"));
+});

+ 26 - 0
test/examples/coroutine/exit_in_coroutine.php

@@ -0,0 +1,26 @@
+<?php
+function route()
+{
+    controller();
+}
+
+function controller()
+{
+    your_code();
+}
+
+function your_code()
+{
+    co::sleep(.001);
+    exit(1);
+}
+
+go(function () {
+    try {
+        route();
+    } catch (\Swoole\ExitException $e) {
+        assert($e->getStatus() === 1);
+        assert($e->getFlags() === SWOOLE_EXIT_IN_COROUTINE);
+        return;
+    }
+});

+ 12 - 0
test/examples/coroutine/exit_with_status.php

@@ -0,0 +1,12 @@
+<?php
+$exit_status = 0;
+go(function () {
+    try {
+        exit(123);
+    } catch (\Swoole\ExitException $e) {
+        global $exit_status;
+        $exit_status = $e->getStatus();
+    }
+});
+swoole_event_wait();
+exit($exit_status);

+ 20 - 0
test/examples/coroutine/fgets.php

@@ -0,0 +1,20 @@
+<?Php
+$fp = fopen(__DIR__ . "/defer_client.php", "r");
+stream_set_chunk_size($fp, 1024);
+
+go(function () use ($fp)
+{
+    for($i = 0; $i<100;$i++) {
+        $r =  co::fgets($fp);
+        if (empty($r) and feof($fp))
+        {
+            //echo "EOF\n";
+            break;
+        }
+        //echo "len=".strlen($r)."\n";
+        echo $r;
+        //echo "---------------------------------------\n";
+        //var_dump($r);
+        //co::sleep(1);
+    }
+});

+ 11 - 0
test/examples/coroutine/fread.php

@@ -0,0 +1,11 @@
+<?php
+use Swoole\Coroutine as co;
+
+$fp = fopen(__DIR__ . "/defer_client.php", "r");
+
+co::create(function () use ($fp)
+{
+    fseek($fp, 256);
+    $r =  co::fread($fp);
+    var_dump($r);
+});

+ 10 - 0
test/examples/coroutine/fwrite.php

@@ -0,0 +1,10 @@
+<?php
+use Swoole\Coroutine as co;
+
+$fp = fopen(__DIR__ . "/test.data", "a+");
+
+co::create(function () use ($fp)
+{
+    $r =  co::fwrite($fp, "hello world\n", 5);
+    var_dump($r);
+});

+ 7 - 0
test/examples/coroutine/gethostbyname.php

@@ -0,0 +1,7 @@
+<?php
+use Swoole\Coroutine as co;
+
+co::create(function() {
+    $ip = co::gethostbyname("www.baidu.com");
+    echo "IP: $ip\n";
+});

+ 53 - 0
test/examples/coroutine/http/server.php

@@ -0,0 +1,53 @@
+<?php
+Co::set([
+    'trace_flags' => SWOOLE_TRACE_HTTP2,
+    'log_level' => 0,
+]);
+go(function () {
+	$server = new Co\Http\Server("127.0.0.1", 9501, false);
+	/**
+	 * 静态文件处理器
+	 */
+	//$server->handle('/static', $server->getStaticHandler());
+	/**
+	 * WebSocket应用
+	 */
+	$server->handle('/websocket', function ($request, $ws) {
+		$ws->upgrade();
+
+        $frame1 = $ws->recv();
+        $frame2 = $ws->recv();
+		var_dump($frame1, $frame2);
+
+		$ws->push("hello world\n");
+
+		while(true) {
+			echo "recv begin:\n";
+			$frame = $ws->recv();
+			if ($frame == false) {
+			    echo "ws client is closed\n";
+                var_dump("Error: ", swoole_last_error());
+			    break;
+            }
+			echo $frame->data ."\n";
+			$ws->push("hello world");
+		}
+	});
+	/**
+	 * Http应用
+	 */
+	$server->handle('/', function ($request, $response) {
+	    var_dump($request);
+		var_dump($request->get);
+		$response->end("<h1>hello world</h1>");
+	});
+
+	$server->handle('/test', function ($request, $response) {
+		var_dump($request->get);
+		$response->end("<h1>Test</h1>");
+	});
+
+	$server->start();
+});
+
+swoole_event_wait();

+ 81 - 0
test/examples/coroutine/http2_client.php

@@ -0,0 +1,81 @@
+<?php
+use Swoole\Coroutine as co;
+
+const TEST = array('get', 'post', 'pipeline');
+//const TEST = array('pipeline');
+//const TEST = array('get',);
+
+CO::set(['trace_flags' => SWOOLE_TRACE_HTTP2, 
+// 'log_level' => SWOOLE_LOG_TRACE,
+
+
+
+]);
+
+
+
+co::create(function () use ($fp)
+{
+    $cli = new co\Http2\Client('127.0.0.1', 9518);
+
+    $cli->set([ 'timeout' => 1, 'package_max_length' => 1024*1024*8]);
+    var_dump($cli->connect());
+
+    if (in_array('get', TEST))
+    {
+        $req = new Swoole\Http2\Request;
+        $req->path = "/index.html";
+        $req->headers = [
+            'host' => "localhost",
+            "user-agent" => 'Chrome/49.0.2587.3',
+            'accept' => 'text/html,application/xhtml+xml,application/xml',
+            'accept-encoding' => 'gzip',
+        ];
+        $req->cookies = ['name' => 'rango', 'email' => '1234@qq.com'];
+        var_dump($cli->send($req));
+
+        $resp = $cli->recv();
+        var_dump($resp);
+    }
+
+    if (in_array('post', TEST))
+    {
+        $req2 = new Swoole\Http2\Request;
+        $req2->path = "/index.php";
+        $req2->headers = [
+            'host' => "localhost",
+            "user-agent" => 'Chrome/49.0.2587.3',
+            'accept' => 'text/html,application/xhtml+xml,application/xml',
+            'accept-encoding' => 'gzip',
+        ];
+        $req2->data = "hello world\n";
+        var_dump($cli->send($req2));
+
+        $resp = $cli->recv();
+        var_dump($resp);
+    }
+
+    if (in_array('pipeline', TEST))
+    {
+        $req3 = new Swoole\Http2\Request;
+        $req3->path = "/index.php";
+        $req3->headers = [
+            'host' => "localhost",
+            "user-agent" => 'Chrome/49.0.2587.3',
+            'accept' => 'text/html,application/xhtml+xml,application/xml',
+            'accept-encoding' => 'gzip',
+        ];
+        $req3->pipeline = true;
+        $req3->method = "POST";
+        $streamId = $cli->send($req3);
+
+        $cli->write($streamId, ['int' => rand(1000, 9999)]);
+        $cli->write($streamId, ['int' => rand(1000, 9999)]);
+        //end stream
+        $cli->write($streamId, ['int' => rand(1000, 9999), 'end' => true], true);
+
+        var_dump($cli->recv());
+    }
+
+//    $cli->close();
+});

+ 40 - 0
test/examples/coroutine/http_backend_serv.php

@@ -0,0 +1,40 @@
+<?php
+/**
+ * @Author: syyuanyizhi@163.com
+    connect refuse: errorCode  111
+    I/O     timeout:errorCode  110
+    http 9510
+    tcp  9511
+
+ */
+class Server
+{
+    public $server;
+
+    public function run()
+    {
+        $this->server = new Swoole\Http\Server("0.0.0.0", 9510);
+        $this->server->set([
+            'worker_num' => 1,
+            'daemonize' => true,
+            'log_file' => '/data/markyuan/swoole.log',
+        ]);
+        $this->server->on('Request', ['Server', 'onRequest']);
+        $this->server->start();
+    }
+    public static function onRequest($request, $response)
+    {
+
+        $response->end('xxxx');
+    }
+
+
+    public static function staticFunc()
+    {
+        echo "in static function";
+    }
+}
+
+$server = new Server();
+
+$server->run();

+ 12 - 0
test/examples/coroutine/http_client.php

@@ -0,0 +1,12 @@
+<?php
+use Swoole\Coroutine as co;
+co::create(function () {
+    $cli = new co\http\client('127.0.0.1', 9501);
+    $cli->setHeaders(['Host' => 'localhost']);
+    $cli->set(['http_proxy_host' => HTTP_PROXY_HOST, 'http_proxy_port' => HTTP_PROXY_PORT]);
+    $result = $cli->get('/get?json=true');
+    var_dump($cli->body);
+//     assert($result);
+//     $ret = json_decode($cli->body, true);
+//     assert(is_array($ret) and $ret['json'] == 'true');
+});

+ 13 - 0
test/examples/coroutine/http_download.php

@@ -0,0 +1,13 @@
+<?php
+go(function () {
+    $host = 'www.swoole.com';
+    $cli = new \Swoole\Coroutine\Http\Client($host, 443, true);
+    $cli->set(['timeout' => -1]);
+    $cli->setHeaders([
+        'Host' => $host,
+        "User-Agent" => 'Chrome/49.0.2587.3',
+        'Accept' => '*',
+        'Accept-Encoding' => 'gzip'
+    ]);
+    $cli->download('/static/files/swoole-logo.svg', __DIR__ . '/logo.svg');
+});

+ 37 - 0
test/examples/coroutine/http_server.php

@@ -0,0 +1,37 @@
+<?php
+ini_set("memory_limit","512M");
+use Swoole\Coroutine as co;
+class Server
+{
+    public $server;
+    public $redisPool = [];
+
+    public function run()
+    {
+        $this->server = new Swoole\Http\Server("0.0.0.0", 9502, SWOOLE_BASE);
+        $this->server->set([
+            'worker_num' => 1,
+        ]);
+
+        // $this->server->on('Connect', [$this, 'onConnect']);
+        $this->server->on('Request', [$this, 'onRequest']);
+//         $this->server->on('Close', [$this, 'onClose']);
+        $this->server->set(['trace_flags' => 1 << 15, 'log_level' => 0]);
+        $this->server->start();
+    }
+
+    public function onRequest($request, $response)
+    {
+        $fd = $request->fd;
+        co::create(function () {
+            co::sleep(0.1);
+        });
+        $response->end(111);
+    }
+}
+
+$server = new Server();
+Swoole\Coroutine::set(array(
+    'max_coroutine' => 1000,
+));
+$server->run();

+ 162 - 0
test/examples/coroutine/httpmulti.php

@@ -0,0 +1,162 @@
+<?php
+/**
+ * @Author: syyuanyizhi@163.com
+    connect refuse: errorCode  111
+    I/O     timeout:errorCode  110
+    http 9510
+    tcp  9511
+
+ */
+class Server
+{
+    public $server;
+
+    public function run()
+    {
+        $this->server = new Swoole\Http\Server("0.0.0.0", 9508);
+        $this->server->set([
+            'worker_num' => 1,
+            'daemonize' => true,
+            'log_file' => '/data/markyuan/swoole.log',
+        ]);
+        $this->server->on('Request', ['Server', 'onRequest']);
+        $this->server->start();
+    }
+
+    private static function https(){
+        //--enable-openssl
+        for($i=0;$i<2;$i++){
+            $cli = new Swoole\Coroutine\Http\Client('0.0.0.0',443,TRUE );
+            $cli->set([ 'timeout' => 1]);
+            $cli->setHeaders([
+                'Host' => "api.mp.qq.com",
+                "User-Agent" => 'Chrome/49.0.2587.3',
+                'Accept' => 'text/html,application/xhtml+xml,application/xml',
+                'Accept-Encoding' => 'gzip',
+            ]);
+            $ret = ($cli->get('/cgi-bin/token?appid=3333&secret=222'.$i.$i.$i.$i.$i));
+            error_log(__LINE__.var_export($cli,true).PHP_EOL,3,'/tmp/markyuan');
+            $cli->close();
+        }
+    }
+
+    private static function http(){
+        error_log(__LINE__.'---------- begin --- http --------------'.PHP_EOL,3,'/tmp/markyuan');
+        for($i=0;$i<2;$i++){
+            $cli = new Swoole\Coroutine\Http\Client('0.0.0.0', 9510);
+            $cli->set([ 'timeout' => 1]);
+            $cli->setHeaders([
+                'Host' => "api.mp.qq.com",
+                "User-Agent" => 'Chrome/49.0.2587.3',
+                'Accept' => 'text/html,application/xhtml+xml,application/xml',
+                'Accept-Encoding' => 'gzip',
+            ]);
+            error_log(__LINE__.var_export($cli,true).PHP_EOL,3,'/tmp/markyuan');
+            $ret = ($cli->get('/cn/token?appid=1FxxxxS9V'.$i.$i.$i.$i.$i));
+            error_log(__LINE__.var_export($ret,true).PHP_EOL,3,'/tmp/markyuan');
+            error_log(__LINE__.var_export($cli,true).PHP_EOL,3,'/tmp/markyuan');
+            $cli->close();
+        }
+        error_log(__LINE__.'---------- end --- http --------------'.PHP_EOL,3,'/tmp/markyuan');
+
+    }
+
+    private static function multihttp(){
+
+        error_log(__LINE__.'---------- begin --- multi --------------'.PHP_EOL,3,'/tmp/markyuan');
+
+        $cliAA= new Swoole\Coroutine\Http\Client('0.0.0.0', 9510);
+        $cliAA->set(['timeout' => 1]);
+        $cliAA->setHeaders([
+            'Host' => "api.mp.qq.com",
+            "User-Agent" => 'Chrome/49.0.2587.3',
+        ]);
+        $cliBB= new Swoole\Coroutine\Http\Client('0.0.0.0', 9510);
+        $cliBB->set([ 'timeout' => 1]);//
+        $cliBB->setHeaders([
+            'Host' => "api.mp.qq.com",
+            "User-Agent" => 'Chrome/49.0.2587.3',
+        ]);
+        error_log(__LINE__.var_export($cliAA,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($cliBB,true).PHP_EOL,3,'/tmp/markyuan');
+        $retAA=$cliAA->setDefer(1);
+        $retBB=$cliBB->setDefer(1);
+        error_log(__LINE__.var_export($retAA,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($retBB,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($cliAA,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($cliBB,true).PHP_EOL,3,'/tmp/markyuan');
+        $retAA = ($cliAA->get('/cn/token?appid=AAA'));
+        $retBB = ($cliBB->get('/cn/token?appid=BBB'));
+        error_log(__LINE__.var_export($retAA,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($retBB,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($cliAA,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($cliBB,true).PHP_EOL,3,'/tmp/markyuan');
+        $retAA=$cliAA->recv();
+        $retBB=$cliBB->recv();
+        error_log(__LINE__.var_export($retAA,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($retBB,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($cliAA,true).PHP_EOL,3,'/tmp/markyuan');
+        error_log(__LINE__.var_export($cliBB,true).PHP_EOL,3,'/tmp/markyuan');
+        $retAA=$cliAA->close();
+        $retBB=$cliBB->close();
+        error_log(__LINE__.'---------- end --- multi --------------'.PHP_EOL,3,'/tmp/markyuan');
+    }
+
+
+
+    private static function tcp(){
+        for($i=0;$i<2;$i++){
+            $tcp_cli = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+            $ret = $tcp_cli ->connect("0.0.0.0", 9511);
+            $ret = $tcp_cli ->send('test for the coro');
+            $ret = $tcp_cli ->recv();
+            $ret=$tcp_cli->close();
+        }
+    }
+
+ private static function coro_dns(){
+    swoole_async_set(array('use_async_resolver'=>1));
+    swoole_async_set(array('dns_cache_refresh_time'=>0));
+    $ret=swoole_async_dns_lookup_coro("www.baidu.com",0.5);
+    error_log(' ip and host '.$host.print_r($ret,true),'3','/home/yuanyizhi/markyuan/markyuan.log');
+    return $ret;
+//  swoole_async_dns_lookup("www.baidu.com", function($host, $ip){
+//  error_log(' ip and host '.$host.'  and  ip '.$ip,'3','/home/yuanyizhi/markyuan/markyuan.log');
+//  });
+    }
+
+
+private static function tcpmulti(){
+        $cliAA = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+        $cliBB = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+        $retAA = $cliAA ->connect("0.0.0.0", 9511);
+        $retBB = $cliBB ->connect("0.0.0.0", 9511);
+        $retAA = $cliAA ->send('test for the coro');
+        $retBB = $cliBB ->send('test for the coro');
+        $retAA = $cliAA->recv();
+        $retBB = $cliBB->recv();
+        $cliAA->close();
+        $cliBB->close();
+    }
+
+    public static function onRequest($request, $response)
+    {
+//        self::multihttp();
+//        self::http();
+        //self::https();
+//        self::tcp();
+      //  self::tcpmulti();
+        $ret=self::coro_dns();
+        $response->end(print_r($ret,true));
+    }
+
+
+    public static function staticFunc()
+    {
+        echo "in static function";
+    }
+}
+
+$server = new Server();
+
+$server->run();

+ 40 - 0
test/examples/coroutine/library/base.php

@@ -0,0 +1,40 @@
+<?php
+class R
+{
+    public function __construct()
+    {
+        $cid = \Swoole\Coroutine::getCid();
+        echo "cid:$cid ".__CLASS__ . '#' . \spl_object_id((object)$this) . ' constructed' . PHP_EOL;
+    }
+    
+    public function __destruct()
+    {
+        $cid = \Swoole\Coroutine::getCid();
+        echo "cid:$cid ".__CLASS__ . '#' . \spl_object_id((object)$this) . ' destructed' . PHP_EOL;
+    }
+}
+
+class Pool extends \Swoole\Coroutine\ObjectPool
+{
+    public function __construct($type)
+    {
+        parent::__construct($type);
+    }
+    
+    public function create()
+    {
+        return new R;
+    }
+}
+
+$pool = new Pool("test");
+go(function() use ($pool){
+    $object = $pool->get();
+    $cid = \Swoole\Coroutine::getCid();
+    echo "cid:$cid ".var_export($object,1)."\n";
+});
+go(function() use ($pool){
+    $object = $pool->get();
+    $cid = \Swoole\Coroutine::getCid();
+    echo "cid:$cid ".var_export($object,1)."\n";
+});

+ 21 - 0
test/examples/coroutine/list_coroutines.php

@@ -0,0 +1,21 @@
+<?php
+foreach(range(1, 100) as $i) {
+    go(function () use ($i) {
+        if ($i % 9 == 7) {
+            return;
+        }
+        while(true) {
+            co::sleep(10);
+            echo "CORO: $i\n";
+        }
+    });
+}
+
+go(function () {
+    while(true) {
+        co::sleep(3);
+        $coros = Co::listCoroutines();
+        $cids = iterator_to_array($coros );
+        var_dump($cids);
+    }
+});

+ 32 - 0
test/examples/coroutine/mysql_chan.php

@@ -0,0 +1,32 @@
+<?php
+
+use Swoole\Coroutine as co;
+
+$chan = new chan(4);
+
+go(function () use ($chan) {
+
+    $db = new co\MySQL();
+    $server = array(
+        'host' => '127.0.0.1',
+        'user' => 'root',
+        'password' => 'root',
+        'database' => 'test',
+    );
+
+    echo "connect\n";
+    $ret1 = $db->connect($server);
+    var_dump($ret1);
+
+    echo "prepare\n";
+    $ret2 = $db->query('SELECT * FROM userinfo WHERE id=3');
+    var_dump($ret2);
+
+    $chan->push($db);
+});
+
+go(function () use ($chan) {
+    $db = $chan->pop();
+    $ret2 = $db->query('SELECT * FROM userinfo WHERE id=3');
+    var_dump($ret2);
+});

+ 16 - 0
test/examples/coroutine/mysql_escape.php

@@ -0,0 +1,16 @@
+<?php
+
+go(function(){
+    $swoole_mysql = new \Swoole\Coroutine\MySQL();
+    
+    $swoole_mysql->connect([
+        'host' => '127.0.0.1',
+        'port' => 3306,
+        'user' => 'root',
+        'password' => 'root',
+        'database' => 'test',
+    ]);
+    $res = $swoole_mysql->escape("");
+    var_dump($res);
+});
+    

+ 14 - 0
test/examples/coroutine/mysql_execute_empty.php

@@ -0,0 +1,14 @@
+<?php
+go(function () {
+    $db = new Swoole\Coroutine\Mysql;
+    $server = [
+        'host'     => '127.0.0.1',
+        'user'     => 'root',
+        'password' => 'root',
+        'database' => 'test'
+    ];
+    $db->connect($server);
+    $stmt = $db->prepare('SELECT * FROM `userinfo`');
+    $ret = $stmt->execute();
+    var_dump($ret);
+});

+ 41 - 0
test/examples/coroutine/mysql_prepare.php

@@ -0,0 +1,41 @@
+<?php
+use Swoole\Coroutine as co;
+
+co::create(function() {
+
+    $db = new co\MySQL();
+    $server = array(
+        'host' => '127.0.0.1',
+        'user' => 'root',
+        'password' => 'root',
+        'database' => 'test',
+    );
+
+    echo "connect\n";
+    $ret1 = $db->connect($server);
+    var_dump($ret1);
+
+    echo "prepare [1]\n";
+    $stmt1 = $db->prepare('SELECT * FROM userinfo WHERE id=?');
+    var_dump($stmt1);
+    if ($stmt1 == false)
+    {
+        var_dump($db->errno, $db->error);
+    }
+
+    echo "execute\n";
+    $ret3 = $stmt1->execute(array(10));
+    var_dump(count($ret3));
+
+    echo "prepare [2]\n";
+    $stmt2 = $db->prepare('SELECT * FROM userinfo WHERE id > ? and level > ?');
+    var_dump($stmt2);
+    if ($stmt2 == false)
+    {
+        var_dump($db->errno, $db->error);
+    }
+
+    echo "execute\n";
+    $ret4 = $stmt2->execute(array(10, 99));
+    var_dump($ret4);
+});

+ 24 - 0
test/examples/coroutine/mysql_prepare_2.php

@@ -0,0 +1,24 @@
+<?php
+
+
+go(function() {
+
+    $db = new Co\MySQL();
+    $server = array(
+        'host' => '127.0.0.1',
+        'user' => 'root',
+        'password' => 'root',
+        'database' => 'test',
+    );
+
+    echo "connect\n";
+    $ret1 = $db->connect($server);
+    var_dump($ret1);
+
+    echo "prepare [1]\n";
+    $stmt1 = $db->prepare('show tables');
+    echo "execute\n";
+    $ret1 = $stmt1->execute([]);
+    var_dump($ret1);
+
+});

+ 28 - 0
test/examples/coroutine/mysql_procedure_exec.php

@@ -0,0 +1,28 @@
+<?php
+
+go(function () {
+    $db = new Swoole\Coroutine\Mysql;
+    $server = [
+        'host' => '127.0.0.1',
+        'user' => 'root',
+        'password' => 'root',
+        'database' => 'test'
+    ];
+
+    $clear = <<<SQL
+    DROP PROCEDURE IF EXISTS `say`
+SQL;
+    $procedure = <<<SQL
+  CREATE DEFINER=`root`@`localhost` PROCEDURE `say`(content varchar(255))
+  BEGIN
+    SELECT concat('you said: \"', content, '\"');
+  END
+SQL;
+
+    $db->connect($server);
+    if ($db->query($clear) && $db->query($procedure)) {
+        $stmt = $db->prepare('CALL say(?)');
+        $ret = $stmt->execute(['hello mysql!']);
+        var_dump(current($ret[0])); // you said: "hello mysql!"
+    }
+});

+ 26 - 0
test/examples/coroutine/mysql_query.php

@@ -0,0 +1,26 @@
+<?php
+use Swoole\Coroutine as co;
+co::set(['trace_flags' => 1]);
+
+co::create(function() {
+
+
+    $function = new ReflectionFunction('title');
+
+    $function->invoke();
+    echo "invoke444\n";
+
+});
+
+function title() {
+    echo "333invoke_________________________________\n";
+    $tcpclient = new Swoole\Coroutine\Client(SWOOLE_SOCK_TCP);
+    var_dump($tcpclient->connect('127.0.0.1', 9501, 1));
+
+}
+
+echo "111\n";
+
+
+echo "222\n";
+co::go();

+ 15 - 0
test/examples/coroutine/mysql_unixsocket.php

@@ -0,0 +1,15 @@
+<?php
+
+go(function(){
+    $db = new Swoole\Coroutine\Mysql;
+    $server = [
+        'host'     => 'unix:/tmp/mysql.sock',
+        'user'     => 'root',
+        'password' => 'root',
+        'database' => 'test'
+    ];
+    $db->connect($server);
+    $stmt = $db->prepare('SELECT * FROM `user` WHERE id=?');
+    $ret = $stmt->execute([1]);
+    var_dump($ret);
+});

+ 20 - 0
test/examples/coroutine/proc_open.php

@@ -0,0 +1,20 @@
+<?php
+Swoole\Runtime::setHookFlags(SWOOLE_HOOK_ALL);
+Swoole\Coroutine\run(function () {
+
+    $descriptorspec = array(
+        0 => array("pipe", "r"),
+        1 => array("pipe", "w"),
+        2 => array("pipe", "w"),
+    );
+
+    $process = proc_open('unknown', $descriptorspec, $pipes);
+
+    var_dump($pipes);
+
+    var_dump(fread($pipes[2], 8192));
+
+    $return_value = proc_close($process);
+
+    echo "command returned $return_value\n";
+});

+ 71 - 0
test/examples/coroutine/reconnect_test.php

@@ -0,0 +1,71 @@
+<?php
+/* new multi implement test */
+$server = new Swoole\Http\Server("127.0.0.1", 9502, SWOOLE_BASE);
+
+$server->set([
+	'worker_num' => 1,
+]);
+
+$server->on('Request', function ($request, $response) {
+
+	/*
+	$mysql = new Swoole\Coroutine\MySQL();
+	$res = $mysql->connect(['host' => '192.168.244.128', 'user' => 'mha_manager', 'password' => 'mhapass', 'database' => 'tt']);
+	if ($res == false) {
+		$response->end("MySQL connect fail!");
+		return;
+	}
+	$res = $mysql->connect(['host' => '192.168.244.128', 'user' => 'mha_manager', 'password' => 'mhapass', 'database' => 'tt']);
+	if ($res == false) {
+		$response->end("MySQL connect fail!");
+		return;
+	}
+	$mysql->close();
+
+	$res = $mysql->connect(['host' => '192.168.244.128', 'user' => 'mha_manager', 'password' => 'mhapass', 'database' => 'tt']);
+	if ($res == false) {
+		$response->end("MySQL connect fail!");
+		return;
+	}
+	$res = $mysql->query('select sleep(1)', 2);
+	var_dump($res);
+
+	$res = $mysql->connect(['host' => '192.168.244.128', 'user' => 'mha_manager', 'password' => 'mhapass', 'database' => 'tt']);
+	if ($res == false) {
+		$response->end("MySQL connect fail!");
+		return;
+	}
+	$res = $mysql->query('select sleep(1)', 2);
+	var_dump($res);
+	*/
+
+	$redis = new Swoole\Coroutine\Redis();
+	$res = $redis->connect('127.0.0.1', 6379);
+	if ($res == false) {
+		$response->end("Redis connect fail!");
+		return;
+	}
+	$res = $redis->connect('127.0.0.1', 6379);
+	if ($res == false) {
+		$response->end("Redis connect fail!");
+		return;
+	}
+	$redis->close();
+	$res = $redis->connect('127.0.0.1', 6379);
+	if ($res == false) {
+		$response->end("Redis connect fail!");
+		return;
+	}
+	$res = $redis->get('key');
+	var_dump($res);
+	$res = $redis->connect('127.0.0.1', 6379);
+	if ($res == false) {
+		$response->end("Redis connect fail!");
+		return;
+	}
+	$res = $redis->get('key');
+	var_dump($res);
+
+	$response->end('Test End');
+});
+$server->start();

+ 8 - 0
test/examples/coroutine/redis/auth.php

@@ -0,0 +1,8 @@
+<?php
+go(function () {
+    $redis = new Swoole\Coroutine\Redis;
+    $redis->connect('127.0.0.1', 6379);
+    $redis->auth('root');
+    $redis->set('key', 'swoole redis work');
+    var_dump($redis->get('key'));
+});

+ 24 - 0
test/examples/coroutine/redis/defer.php

@@ -0,0 +1,24 @@
+<?php
+
+const REDIS_SERVER_HOST = '127.0.0.1';
+const REDIS_SERVER_PORT = 6379;
+
+
+go(function () {
+    $redis = new Swoole\Coroutine\Redis();
+    $redis->connect(REDIS_SERVER_HOST, REDIS_SERVER_PORT);
+    $redis->setDefer();
+    $redis->set('key1', 'value');
+
+    $redis2 = new Swoole\Coroutine\Redis();
+    $redis2->connect(REDIS_SERVER_HOST, REDIS_SERVER_PORT);
+    $redis2->setDefer();
+    $redis2->get('key1');
+
+    $result1 = $redis->recv();
+    $result2 = $redis2->recv();
+
+    var_dump($result1, $result2);
+});
+
+

+ 0 - 0
test/examples/coroutine/redis/eval.php


Niektóre pliki nie zostały wyświetlone z powodu dużej ilości zmienionych plików