在PHP中等待具有增强格式的apns的错误

时间:2012-09-30 12:18:33

标签: php stream push-notification apple-push-notifications

我们正在使用easy-apns的修改版本来发送推送消息。使用增强的推送消息格式,如果发生错误,Apple服务器会响应,如果一切顺利,则无效。

问题是我们必须在每封邮件发送一段时间后等待错误。例如,如果我们在1秒后没有收到任何回复,我们假设一切正常。

使用20000个推送消息,这需要太长时间。有什么方法可以更快地听错误吗?例如,发送到1000个设备,然后侦听错误?如果连接关闭会发生什么,我还能读取错误响应吗?

理想的是某种异步写作和阅读,但我认为这是不可能的。

以下是相应的代码:

    $fp = $this->connect();

    $expiry = time()+60*60;

    // construct message
    $msg = chr(1).pack("N",$batchid).pack("N",$expiry).pack("n",32).pack('H*',$devicetoken).pack("n",strlen($payload)).$payload;

    // send message to Apple
    $fwrite = fwrite($fp, $msg);

    if(!$fwrite) {
        // connection has been closed
        $this->disconnect();
        throw new Exception("Connection closed");

    } else {
        // read response from Apple

        // Timeout. 1 million micro seconds = 1 second
        $tv_sec = 1;
        $tv_usec = 0;

        $r = array($fp);
        $we = null; // Temporaries. "Only variables can be passed as reference."

        // PROBLEM: this method waits for $tv_sec seconds for a response
        $numChanged = stream_select($r, $we, $we, $tv_sec, $tv_usec);

        if( $numChanged === false ) {
            throw new Exception("Failed selecting stream to read.");
        } elseif ( $numChanged > 0 ) {

            $command = ord( fread($fp, 1) );
            $status = ord( fread($fp, 1) );
            $identifier = implode('', unpack("N", fread($fp, 4)));

            if( $status > 0 ) {

                // The socket has also been closed. Cause reopening in the loop outside.
                $this->disconnect();
                throw new MessageException("APNS responded with status $status: {$this->statusDesc[$status]} ($devicetoken).".microtime(), $status);

            } else {
                // unknown response, assume ok
            }

        } else {
            // no response, assume ok
        }
    }

0 个答案:

没有答案