发送大量通知

时间:2015-12-22 11:12:19

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

我需要同时发送数千(实际上是10000个)推送通知,为此,我检查了StackOverflow并找到了这两个问题:

我使用php实现了我的推送系统:

    // Create the payload body
    $body['aps'] = [
        'alert' => $notification->getMessage(),//$notification is just a notification model, where getMessage() returns the message I want to send as string
        'sound' => 'default'
    ];

    // Encode the payload as JSON
    $payload = json_encode($body);

    $fp = self::createSocket();
    foreach($devices as $device) {
        $token = $device->getToken();
        $msg = chr(0) . pack('n', 32) . pack('H*', str_replace(' ', '', $token)) . pack('n', strlen($payload)) . $payload;
        if(!self::sendSSLMessage($fp, $msg)){
        //$msg is a parameter of the method, it's the message as string
            fclose($fp);
            $fp = self::createSocket();
        }else{
           //Here I log "n notification sent" every 100 notifications
        }
     }
     fclose($fp);

以下是createSocket()方法:

private static function createSocket(){
    $ctx = stream_context_create();
    stream_context_set_option($ctx, 'ssl', 'local_cert', PUSH_IOS_CERTIFICAT_LOCATION);
    stream_context_set_option($ctx, 'ssl', 'passphrase', PUSH_IOS_PARAPHRASE);
    // Open a connection to the APNS server
    $fp = stream_socket_client(
        'ssl://gateway.push.apple.com:2195', $err,
        $errstr, 60, STREAM_CLIENT_CONNECT, $ctx);
    stream_set_blocking ($fp, 0);
    if (!$fp) {
        FileLog::log("Ios failed to connect: $err $errstr");
    }
    return $fp;
}

sendSSLMessage()方法:

private static function sendSSLMessage($fp, $msg, $tries = 0){
        if($tries >= 10){
            return false;
        }

        return fwrite($fp, $msg, strlen($msg)) ? self::sendSSLMessage($fp, $msg, $tries++) : true;
    }

我没有收到苹果的任何错误消息,除了没有人收到通知外,一切都很好。

在此之前,我正在使用一种方法为每条消息创建一个套接字连接并在发送消息后关闭它,但它太慢了所以我们决定改变它,所以我知道它不是客户端相关问题。

1 个答案:

答案 0 :(得分:0)

您必须首先创建$fp套接字,然后将其传递给sendSSLMessage

// initally create Socket here
$fp = self::createSocket();

foreach($devices as $device) {
    $token = $device->getToken();
    $msg = chr(0) . pack('n', 32) . pack('H*', str_replace(' ', '', $token)) . pack('n', strlen($payload)) . $payload;

    if(!self::sendSSLMessage($fp, $msg)){
        fclose($fp);
        $fp = self::createSocket();
    }
}
fclose($fp);

<强>更新

// define in $body['aps'] message with sub array like this
$message = $notification->getMessage();
$body['aps'] = array(
            'alert' => array(
                      'body' => $message,
            ),
            'sound' => 'default',
);