通过PHP与APNS持久连接

Luk*_*kas 5 php push-notification apple-push-notifications ios

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

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

没有这个标志的版本正在运行,但我担心APNS会在我输入生产证书等时阻止我(这里描述).提前致谢.

Mar*_*lin 6

根据预定义常量的PHP文档,使用带有APNS连接的STREAM_CLIENT_PERSISTENT 应该在页面加载之间保持连接活动.这是APNS连接的要求,因为它WILL,因为它发送有效载荷服务攻击潜在的拒绝后,认为任何断开掐死你.

如果您在presisitent连接之外的客户端遇到任何问题,您可能需要尝试以下操作,因为这是我迄今为止在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";
}

?>
Run Code Online (Sandbox Code Playgroud)

消息来源:如何开始使用APNS for iPhone或iTouch

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

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