fread issue with Stream Context

匆匆过客 提交于 2019-12-13 07:15:34

问题


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

Notification gets sent fine though.


回答1:


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.

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


来源:https://stackoverflow.com/questions/42343382/fread-issue-with-stream-context

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!