流上下文的问题

时间:2017-02-20 11:30:20

标签: php fread

我发送iOS通知,并在苹果服务器的响应中使用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)

你很可能在$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
    }
}