$tcpReturn=(yield $this->tcpTest());
$udpReturn=(yield $this->udpTest());
$httpReturn=(yield $this->httpTest());
public function tcpTest(){
$ip = '127.0.0.1';
$port = '9905';
$data = 'test';
$timeout = 0.5; //second
yield new Swoole\Client\TCP($ip, $port, $data, $timeout);
}
public function udpTest(){
$ip = '127.0.0.1';
$port = '9905';
$data = 'test';
$timeout = 0.5; //second
yield new Swoole\Client\UDP($ip, $port, $data, $timeout);
}
public function httpTest(){
$url='http://www.qq.com';
$httpRequest= new Swoole\Client\HTTP($url);
$data='testdata';
$header = array(
'Content-Length' => 12345,
);
yield $httpRequest->get($url); //yield $httpRequest->post($path, $data, $header);
}
这段代码是TSF的启动部分。
yield网上最常见的场景是迭代,用来减少内存内存消耗。
但是在基于swoole或者其他协程场景的时候大量使用了yield,比如在函数前加一个yield,很明显已经不是迭代器的用法了,这些yield到底是如何发挥作用的?
这是一种协程栈的使用方法。
通常我们使用协程,只是单个迭代器函数配合
send
数据,但是对于相对复杂的业务场景,纯粹使用单个函数,会使得函数过于庞大而复杂。但是纯粹的方法调用嵌套,又无法然最外层调用的函数触发最内层函数的迭代。所以就有了协程栈的设计思路。协程栈简单的来说,就是最内层的函数通过迭代方法,逐步将迭代器向上传递到最外层函数,再让最外层函数对这些迭代器进行操作,实现复杂逻辑上的协程。