async.php 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞
  3. //$client->set(array(
  4. // 'socket_buffer_size' => 1024 * 1024 * 2,
  5. // 'open_eof_check' => true,
  6. // 'package_eof' => "\r\n\r\n",
  7. //));
  8. $client->_count = 0;
  9. $client->on("connect", function(swoole_client $cli) {
  10. //swoole_timer_clear($dpcli->timer);
  11. $cli->send("GET / HTTP/1.1\r\n\r\n");
  12. //$dpcli->sendfile(__DIR__.'/test.txt');
  13. //$dpcli->_count = 0;
  14. });
  15. $client->on("receive", function(swoole_client $cli, $data){
  16. echo "Receive: $data";
  17. $cli->_count++;
  18. if ($cli->_count > 5)
  19. {
  20. //睡眠模式,不再接收新的数据
  21. echo "count=10, sleep(5000ms)\n";
  22. $cli->sleep();
  23. $cli->_count = 0;
  24. swoole_timer_after(5000, function() use ($cli) {
  25. //唤醒
  26. $cli->wakeup();
  27. });
  28. //$dpcli->close();
  29. return;
  30. }
  31. else
  32. {
  33. $cli->send(str_repeat('A', 100)."\n");
  34. }
  35. });
  36. $client->on("error", function(swoole_client $cli){
  37. echo "error\n";
  38. });
  39. $client->on("close", function(swoole_client $cli){
  40. echo "Connection close\n";
  41. });
  42. $client->connect('127.0.0.1', 9501);
  43. //$client->timer = swoole_timer_after(1000, function () use ($client) {
  44. // echo "socket timeout\n";
  45. // $client->close();
  46. //});
  47. //echo "connect to 127.0.0.1:9501\n";