【问题标题】:fread() issue with Stream Context流上下文的 fread() 问题
【发布时间】:2017-02-20 11:30:20
【问题描述】:

我的应用程序发送 iOS 通知。我使用fread() 检查Apple 服务器的响应是否有错误。但是,代码会陷入循环或继续加载。

$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);

我做错了什么?

【问题讨论】:

  • 你的问题是......
  • 我的问题,为什么这个过程没有完成。它一直在处理。
  • 我会添加一些调试行来确定它有多远以及它在哪里停止/卡住。当我使用不显示在屏幕上的 PHP 脚本时,我会从脚本中的不同点向自己发送电子邮件,然后我可以更具体地弄清楚发生了什么。

标签: php fread


【解决方案1】:

您很可能阻塞了$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
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-26
    • 2021-08-09
    • 1970-01-01
    • 2011-03-11
    • 1970-01-01
    • 2011-04-26
    • 2011-12-01
    • 1970-01-01
    相关资源
    最近更新 更多