EasySwoole中使用异步客户端

为方便测试,我们以RPC中的例子来实现服务端,具体请看文档RPC章节。

纯原生异步

  1. public static function mainServerCreate(ServerManager $server,EventRegister $register): void
  2. {
  3. // TODO: Implement mainServerCreate() method.
  4. $tcp = $server->addServer('tcp',9502);
  5. $tcp->registerDefaultOnReceive(new \Tcp\Parser());
  6. $register->add($register::onWorkerStart,function ($ser,$workerId){
  7. if($workerId == 0){
  8. $client = new \swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC);
  9. $client->on("connect", function(\swoole_client $cli) {
  10. $cli->send("test:delay");
  11. });
  12. $client->on("receive", function(\swoole_client $cli, $data){
  13. echo "Receive: $data";
  14. $cli->send("test:delay");
  15. sleep(1);
  16. });
  17. $client->on("error", function(\swoole_client $cli){
  18. echo "error\n";
  19. });
  20. $client->on("close", function(\swoole_client $cli){
  21. echo "Connection close\n";
  22. });
  23. $client->connect('127.0.0.1', 9502);
  24. }
  25. });
  26. }

伪异步-eventLoop

利用swoole自带的事件循环,实现异步

  1. public static function mainServerCreate(ServerManager $server,EventRegister $register): void
  2. {
  3. // TODO: Implement mainServerCreate() method.
  4. $tcp = $server->addServer('tcp',9502);
  5. $tcp->registerDefaultOnReceive(new \Tcp\Parser());
  6. $register->add($register::onWorkerStart,function ($ser,$workerId){
  7. if($workerId == 0){
  8. $client = new \swoole_client(SWOOLE_SOCK_TCP);
  9. $client->connect('127.0.0.1', 9502);
  10. //该出send是为了触发服务端主动返回消息,方便直观测试
  11. $client->send("test:delay");
  12. swoole_event_add($client->sock,function()use($client){
  13. //服务端中,在\Tcp\Parser中,因为你发test:delay命令,是依旧会先给你返回\n,因此请做下空判定
  14. $data = trim($client->recv());
  15. if(!empty($data)){
  16. var_dump('rec from ser');
  17. $client->send("test:delay");
  18. }
  19. });
  20. }
  21. });
  22. }

伪异步-socket select

  1. public static function mainServerCreate(ServerManager $server,EventRegister $register): void
  2. {
  3. // TODO: Implement mainServerCreate() method.
  4. $tcp = $server->addServer('tcp',9502);
  5. $tcp->registerDefaultOnReceive(new \Tcp\Parser());
  6. $register->add($register::onWorkerStart,function ($ser,$workerId){
  7. if($workerId == 0){
  8. $client = new \swoole_client(SWOOLE_SOCK_TCP);
  9. $client->connect('127.0.0.1', 9502);
  10. //该出send是为了触发服务端主动返回消息,方便直观测试
  11. $client->send("test:delay");
  12. Timer::loop(100,function ()use($client){
  13. $write = $error = array();
  14. $read = [$client];
  15. $n = swoole_client_select($read, $write, $error, 0.01);
  16. if($n > 0){
  17. $data = trim($client->recv());
  18. if(!empty($data)){
  19. $client->send("test:delay");
  20. var_dump('rec:'.$data);
  21. }
  22. }
  23. });
  24. }
  25. });
  26. }