同步异步主要指的是消息通知的方式
同步:调用者一直等被调用者返回
异步: 调用者不等被调用者返回,直接继续执行
$content = stream_context_create(['http' => ['timeout' => 3]]);
$resp_ip = @file_get_contents("http://ip.taobao.com/service/getIpInfo.php?ip={$req_ip}", false, $content);
function SocketPost($data, $target)
{
$url_info = parse_url($target);
$httpheader = "POST " . $url_info['path'] . " HTTP/1.0\r\n";
$httpheader .= "Host:" . $url_info['host'] . "\r\n";
$httpheader .= "Content-Type:application/x-www-form-urlencoded\r\n";
$httpheader .= "Content-Length:" . strlen($data) . "\r\n";
$httpheader .= "Connection:close\r\n\r\n";
//$httpheader .= "Connection:Keep-Alive\r\n\r\n";
$httpheader .= $data;
$fd = fsockopen($url_info['host'], 80);
fwrite($fd, $httpheader);
usleep(10000); // 这一句也是关键,如果没有这延时,可能在nginx服务器上就无法执行成功
$gets = "";
while (!feof($fd)) {
$gets .= fread($fd, 128);
}
fclose($fd);
// 如果不判断返回值,底下的可以注释
if ($gets != '') {
$start = strpos($gets, '<?xml');
if ($start > 0) {
$gets = substr($gets, $start);
}
}
return $gets;
}
$post_data = 'aa=3333';
$target = 'http://localhost/lianxi/1xiaoyu/default1.php';
$res = SocketPost($post_data, $target);
var_dump($res);
/**
* 发起异步get请求,忽略返回值
* @param string $url
* @param array $data
*/
function socketGet($url, $data = [])
{
$query_str = '';
if ($data) {
foreach($data as $k => $v){
$query_str .= ($k . "=" . $v . "&");
}
}
$info = parse_url($url);
$head = "GET ".$info['path']."?".$query_str." HTTP/1.0\r\n";
$head .= "Host: ".$info['host']."\r\n";
$head .= "\r\n";
$fp = fsockopen($info["host"], 80);
fwrite($fp, $head);
usleep(10000); // 这一句也是关键,如果没有这延时,可能在nginx服务器上就无法执行成功
// $response = '';
// while($row=fread($fp, 4096)){
// $response .= $row;
// }
fclose($fp);
// return $response;
}
php异步请求的几种方式:php异步请求的几种方式
常用异步方式:
1、ajax
2、fsockopen
3、队列 + 推送