5

PHP利用fscckopen实现异步处理方法教程

 2 years ago
source link: https://www.huhexian.com/28217.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

PHP利用fscckopen实现异步处理方法教程

2022-02-2213:58:32评论1104字

用fscckopen实现异步调用php , 这样客户端请求时就可以秒开,无阻塞,把一些耗时的任务放在后台运行。具体请参考原文:使用fscok实现异步调用PHP

文件test.php

我简化成只用GET方法。方便理解。并且调用同一页面,逻辑上调用其它页面可能会更好一点。不过测试没发现问题。

  1. <?php
  2. ignore_user_abort(TRUE); //如果客户端断开连接,不会引起脚本abort.
  3. set_time_limit(0);//取消脚本执行延时上限
  4. if($_GET){
  5. sleep(10);
  6. writelog("get=" . $_GET['get']); //10秒后创建log.txt
  7. exit;
  8. $url="http://127.0.0.1/test.php?get=1";
  9. triggerRequest($url);
  10. echo "success";
  11. function triggerRequest($url){
  12. $method = "GET"; //可以通过POST或者GET传递一些参数给要触发的脚本
  13. $url_array = parse_url($url); //获取URL信息,以便平凑HTTP HEADER
  14. $port = isset($url_array['port'])? $url_array['port'] : 80;
  15. $fp = fsockopen($url_array['host'], $port, $errno, $errstr, 30);
  16. if (!$fp) {
  17. return FALSE;
  18. $getPath = $url_array['path'] ."?". $url_array['query'];
  19. $header = $method . " " . $getPath;
  20. $header .= " HTTP/1.1\r\n";
  21. $header .= "Host: ". $url_array['host'] . "\r\n"; //HTTP 1.1 Host域不能省略
  22. $header .= "Connection:Close\r\n\r\n";
  23. fwrite($fp, $header);
  24. //echo fread($fp, 1024); //我们不关心服务器返回. 关闭这里才不会阻塞
  25. fclose($fp);
  26. return true;
  27. function writelog($message) {
  28. $path = './log.txt';
  29. $handler = fopen($path, 'w+b');
  30. if ($handler) {
  31. $success = fwrite($handler, $message);
  32. fclose($handler);

在php-fpm fastcgi下,也可以用fastcgi_finish_request实现异步非阻塞。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK