PHP的异步、并行、高性能网络通信引擎Swoole发布了2.1.0版本。新版本提供了全新的简称API,全面支持Coroutine+Channel特性,为PHP语言带来全新的编程模型。Swoole2.1的API借鉴了Go语言,在此向Go语言开发团队致敬。Coroutinego(function(){co::sleep(0.5);echo"hello";});go("test");go([$object,"method"]);Channel$chan=newchan(128);$chan->push(1234);$chan->push(1234.56);$chan->push("helloworld");$chan->push(["helloworld"]);$chan->push(新标准类);$chan->push(fopen("test.txt","r+"));while($chan->pop());不像Go语言的chan,因为PHP是动态语言,所以任何类型的Variables都可以发布到channel中。频道选择$c1=newchan(3);$c2=newchan(2);$c3=newchan(2);$c4=newchan(2);$c3->push(3);$c3->push(3.1415);$c4->push(3);$c4->push(3.1415);go(function()使用($c1,$c2,$c3,$c4){echo"select\n";for($i=0;$i<1;$i++){$read_list=[$c1,$c2];$write_list=[$c3,$c4];//$write_list=null;$result=chan::select($read_list,$write_list,5);var_dump($result,$read_list,$write_list);foreach($read_listas$ch){var_dump($ch->pop());}foreach($write_list作为$ch){var_dump($ch->push(666));}echo"exit\n";}});go(function()use($c3,$c4){echo"producer\n";co::sleep(1);$data=$c3->pop();echo"pop[1]\n";var_dump($data);});go(function(){co::sleep(10);});go(function()use($c1,$c2){co::sleep(1);$c1->push("resume");$c2->push("hello");});MySQLClientgo(function(){$db=newCo\MySQL();$server=array('host'=>'127.0.0.1','user'=>'root','password'=>'root','数据库'=>'测试',);$db->connect($server);$result=$db->query('SELECT*FROMuserinfoWHEREid=3');var_dump($result);});RedisClientgo(function(){$redis=newCo\Redis;$res=$redis->connect('127.0.0.1',6379);$ret=$redis->set('key','value');var_dump($redis->get('key'));});HttpClientgo(function(){$http=newCo\Http\Client("www.google.com",443,true);$http->setHeaders(function(){});$ret=$http->get('/');var_dump($http->body);});Http2Clientgo(function(){$http=newCo\Http2\Client("www.google.com",443,true);$req=newco\Http2\Request;$req->path="/index.html";$req->headers=['主机'=>"www.google.com","user-agent"=>'Chrome/49.0.2587.3','accept'=>'text/html,application/xhtml+xml,application/xml','accept-encoding'=>'gzip',];$req->cookies=['name'=>'rango','email'=>'rango@swoole.com'];$ret=$http->发送($req);var_dump($http->recv());});其他APIco::sleep(100);co::fread($fp);co::fwrite($fp,"helloworld");co::gethostbyname('www.google.com');服务器$server=newCo\Http\Server('127.0.0.1',9501);$server->on('Request',function($request,$response){$http=newCo\Http\Client("www.google.com",443,true);$http->setHeaders(function(){"X-Power-By"=>"Swoole/2.1.0",});$ret=$http->get('/');if($ret){$response->end($http->body);}else{$response->end("recvfailederror:{$http->errCode}");}});$server->start();Swoole提供了很多Co\Server、Co\WebSocket\Server、Co\Http\Server、Co\Redis\Server,一共4个支持协程的Server类,你可以在这些服务器程序中使用协程API
