async_client.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. <?php
  2. function send(swoole_client $cli)
  3. {
  4. $data = array(
  5. 'str1' => str_repeat('A', rand(100000, 900000)),
  6. 'str2' => str_repeat('B', rand(100000, 900000)),
  7. 'str3' => str_repeat('C', rand(10000, 90000)),
  8. );
  9. $data['int1'] = rand(100000, 999999);
  10. $sendStr = serialize($data);
  11. $sendData = pack('N', strlen($sendStr)) . $sendStr;
  12. $cli->send($sendData);
  13. echo "send length=" . strlen($sendData) . ", SerId={$data['int1']}\n";
  14. }
  15. $client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_ASYNC); //异步非阻塞
  16. $client->set(array(
  17. 'open_length_check' => 1,
  18. 'package_length_type' => 'N',
  19. 'package_length_offset' => 0, //第N个字节是包长度的值
  20. 'package_body_offset' => 4, //第几个字节开始计算长度
  21. 'package_max_length' => 2000000, //协议最大长度
  22. ));
  23. $client->on("connect", function(swoole_client $cli) {
  24. send($cli);
  25. });
  26. $client->on("receive", function (swoole_client $cli, $data) {
  27. $resp = unserialize(substr($data, 4));
  28. echo "recv length=" . strlen($data) . ", SerId={$resp['int1']}\n".str_repeat('-', 60)."\n";
  29. $cli->close();
  30. // sleep(1);
  31. //usleep(200000);
  32. //send($cli);
  33. });
  34. $client->on("error", function(swoole_client $cli){
  35. echo "error\n";
  36. });
  37. $client->on("close", function(swoole_client $cli){
  38. echo "Connection close\n";
  39. });
  40. $client->connect('127.0.0.1', 9501);