通过 PHP 到 APNS 的持久连接


Persistent connection via PHP to APNS

我知道SO上有很多帖子可以解决这个问题,不幸的是,我在PHP编程方面不是那么高级,而且我有一个问题在其他地方没有得到回答:

许多 Apple 推送通知教程通过 stream_socket_client() 创建连接。但他们中的大多数都缺少"STREAM_CLIENT_PERSISTENT"标志。这个标志会让连接真正持久吗?如果是这样,什么时候关闭?文档说它也将在页面重新加载时保持连接。这是否取决于会话?

没有此标志的版本可以工作,但我担心一旦我输入生产证书等,APNS 就会阻止我(在此处描述)。提前谢谢。

根据有关预定义常量的 PHP 文档,将STREAM_CLIENT_PERSISTENT与 APNS 连接一起使用应该在页面加载之间保持连接处于活动状态。这是 APNS 连接的一项要求,因为它会在发送有效负载后将任何断开连接视为潜在的拒绝服务攻击时限制您。

如果您在预先连接之外的客户端有任何问题,您可能需要尝试以下方法,因为这是我迄今为止在 PHP 中处理 APNS 连接的最佳方式。这使用来自 PHPXMLRPC 的客户端,因此您必须下载该软件包。

<?php
include '../vendors/xmlrpc.inc';
$hostName = 'localhost'; # Your services endpoint here.
$rpcPath = '';
$port = 7077;
if($_GET['action'] == 'provisioning')
{
    $echoString = new xmlrpcmsg(
        'provision',
        array(
            php_xmlrpc_encode('appid'),
            php_xmlrpc_encode('/path/to/certificate.pem'),
            php_xmlrpc_encode('sandbox'),
            php_xmlrpc_encode(100)
        )
    );
    $continue = TRUE;
}
if($_GET['action'] == 'notify')
{
    $echoString = new xmlrpcmsg(
        'notify',
        array(
            php_xmlrpc_encode('paparazzme'),
            php_xmlrpc_encode(array('6bcda...', '7c008...')),
            php_xmlrpc_encode(array(array("aps" => array("alert" => "Hello User 1" )), array("aps" => array("alert" => "Hello User 2" ))))
        )
    );
    $continue = TRUE;
}
if($continue == true)
{
    # Create a client handle and send request
    $client = new xmlrpc_client($rpcPath, $hostName, $port);
    # A little verbose debug
    $client->setDebug(2);
    # The response
    $response = &$client->send($echoString);
    # Check if response is good
    if (! $response->faultCode())
        print "'nReturned string is: " . php_xmlrpc_decode($response->value()) . "'n";
    else
        print "An error occurred: 'nCode: " . $response->faultCode() . " Reason: '" . htmlspecialchars($response->faultString()) . "''n";
}
?>

来源:如何开始使用适用于 iPhone 或 iTouch 的 APNS

我想花时间指出,我没有测试任何这些代码,我现在没有iPhone应用程序来测试它,所以我可以告诉你这是否真的有效。

如果对您可行,我建议您改用 Uban Airship,因为他们确实每月为每个客户提供 250,000 次免费推送,并为您处理与 APN 服务器的连接,从那里您可以使用他们的 API 与您的客户交谈。