fread问题与流上下文

问题描述:

我发送iOS通知,并在作出响应从苹果服务器检查是否有一些错误使用fread()但代码卡住了一些循环或只是加载和加载。无法弄清楚原因。fread问题与流上下文

$apnsHost = 'gateway.sandbox.push.apple.com'; 
$apnsCert = 'j_.pem'; 
$apnsPort = 2195; 
$apnsPass = ''; 
$notification = "hey"; 

$streamContext = stream_context_create(); 
stream_context_set_option($streamContext, 'ssl', 'local_cert', $apnsCert); 
stream_context_set_option($streamContext, 'ssl', 'passphrase', $apnsPass); 
$apns = stream_socket_client('ssl://'.$apnsHost.':'.$apnsPort, $error, $errorString, 2, STREAM_CLIENT_CONNECT, $streamContext); 


$payload['aps'] = array('alert' => $notification, 'sound' => 'default','link'=>'https://google.com','content-available'=>"1"); 
$output = json_encode($payload); 
$token = pack('H*', str_replace(' ', '', "device_token")); 
$apnsMessage = chr(0).chr(0).chr(32).$token.chr(0).chr(strlen($output)).$output; 
fwrite($apns, $apnsMessage);  
$response = fread($apns,6); 
fclose($apns); 

虽然通知得到了很好的发送。

+1

而你的问题是...... –

+0

我的问题,为什么过程没有完成。它不断处理。 –

+0

我会抛出一些调试行来判断它到底有多远以及它停止/卡住的位置。当我使用不显示在屏幕上的PHP脚本时,我会从脚本中的不同点发送自己的电子邮件,然后我可以更具体地了解发生的事情。 – jsherk

你很可能在$response = fread($apns,6);上被阻止,就像类似的问题所解释的那样,成功时没有字节被返回来读取,所以它会永远等待6个字节读取。

最好像ApnsPHP过去所做的那样,并使用select_stream()来确定是否有任何要读取的内容,之前试图读取它。尝试更换$response = fread($apns,6);与:

$read = array($apns); 
$null = NULL; 
//wait a quarter second to see if $apns has something to read 
$nChangedStreams = @stream_select($read, $null, $null, 0, 250000); 
if ($nChangedStreams === false) { 
    //ERROR: Unable to wait for a stream availability. 
} else if ($nChangedStreams > 0) { 
    //there is something to read, time to call fread 
    $response = fread($apns,6); 
    $response = unpack('Ccommand/Cstatus_code/Nidentifier', $response); 
    //do something with $response like: 
    if ($response['status_code'] == '8') { //8-Invalid token 
     //delete token 
    } 
}