简体   繁体   中英

fread issue with Stream Context

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM