流上下文的可怕问题 [英] fread issue with Stream Context

查看:62
本文介绍了流上下文的可怕问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在发送iOS通知,并作为响应来自Apple服务器,通过使用fread()检查是否存在某些错误,但代码陷入某些循环或只是加载和加载.无法找出原因.

I am sending iOS notification and in response from apple server checking if there was some error by using fread() but the code gets stuck in some loop or just loading and loading. Couldn't figure out the reason.

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

不过通知发送得很好.

推荐答案

您很可能在$response = fread($apns,6);上进行阻止,如类似问题中所述,成功后不会返回任何字节以供读取,因此它将永远坐在那里等待6个字节读取.

You're most likely blocking on$response = fread($apns,6); as is explained in similar questions, on success no bytes are returned to be read so it'll sit there forever waiting for 6 bytes to read.

最好做得像ApnsPHP过去所做的那样,并使用select_stream()确定是否有任何要读取的内容,然后再 尝试读取它.尝试将$response = fread($apns,6);替换为:

It's better to do like ApnsPHP has done in the past, and use select_stream() to determine if there is anything to read, before trying to read it. Try replacing $response = fread($apns,6); with:

$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
    }
}

这篇关于流上下文的可怕问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆