1

我正在尝试为多个设备发送通知。所以我得到一个数组的令牌,打开连接,循环发送通知,关闭连接。

但是,在 9-10 个设备之后,它会停止发送。我相信苹果会以某种方式断开连接。

这是我的代码:

$message = 'Push';
$passphrase = 'mypass';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'MyPemFile.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);

// Open a connection to the APNS server
$fp = stream_socket_client(
    'ssl://gateway.push.apple.com:2195', $err,
    $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
    exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to Apple service. ' . PHP_EOL;

// Encode the payload as JSON
$body['aps'] = array(
    'alert' => $message,
    'sound' => 'default'
    );
$payload = json_encode($body);

$result = 'Start'.PHP_EOL;
$tokenArray = array('mytoken');
foreach ($tokenArray as $item)
{
// Build the binary notification
$msg = chr(0).pack('n', 32).pack('H*', $item).pack('n', strlen($payload)).$payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
    echo 'Failed message'.PHP_EOL;
else
    echo 'Successful message'.PHP_EOL;
}
// Close the connection to the server
fclose($fp);

我的代码有问题吗?我想我需要打开一次连接,发送通知然后关闭。我应该用多个令牌做 fwrite() 吗?我不知道如何。任何想法或解决方案都被接受。

顺便说一句,答案是这样的:

Successful message  
Successful message  
Successful message  
Successful message  
Successful message  
Successful message  
Successful message  
Successful message  
Successful message  
Successful message
Failed message
Failed message
Failed message
Failed message
Failed message
...
Failed message

PS我有相同代码的字符问题,但在另一个问题中解决了,这是另一个问题,不是重复的。

4

1 回答 1

1

第一条失败的消息可能有问题,此时 Apple 将关闭连接以向您发出存在问题的信号。如果您使用的是增强格式,您有机会在 Apple 关闭连接之前获得一些反馈,以查看您发送的通知有什么问题。发生这种情况后,您必须重新建立连接以发送更多消息。

它可能失败的原因有很多。您可能发送了无效的设备令牌,您的有效负载可能无效或长度错误等。

最好查看 APNS 的文档:http: //developer.apple.com/library/mac/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/CommunicatingWIthAPS/CommunicatingWIthAPS.html

于 2012-10-03T12:48:39.663 回答