APNS - 通知推送 ios:连接被对等方重置 PHP

APNS - notifications push ios: Connection reset by peer PHP

我的推送通知工作正常。但有时,它从无处开始给出错误:

stream_socket_client():SSL:连接被对等方重置

Weird thing is i don't have to do anything to resolve it but wait. After sometime, it starts working back again.

我知道这是一个 重复 的许多问题,例如: notifications-push-ios-connection-reset-by-peer 但是 none 解决了我的问题。

我正在使用 PHP stream_socket_client 生成套接字连接

正在使用的代码是:

 <?php
ini_set('display_errors','On'); 
error_reporting(E_ALL);
$deviceToken= 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';      
$passphrase = ' ';
$message = 'my first notification';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
    'ssl://gateway.sandbox.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 APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
    'alert' => $message,
    'sound' => 'default'
    );

// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
    echo 'Message not delivered' . PHP_EOL;
else
    echo 'Message successfully delivered' . PHP_EOL;
// Close the connection
}

我真的说不出主要原因。

但请确保您没有做错以下任何事情:

  • 不要并行连接很多。在发送推送通知后重新使用相同的连接或关闭连接。实际上,服务器对最大并行连接数有限制,一旦达到阈值,这可能会给您带来麻烦。苹果还建议保持连接打开,除非你知道它会空闲。

Keep your connections with APNs open across multiple notifications; don’t repeatedly open and close connections. APNs treats rapid connection and disconnection as a denial-of-service attack. You should leave a connection open unless you know it will be idle for an extended period of time—for example, if you only send notifications to your users once a day it is ok to use a new connection each day.

  • 不要向 LIVE APNS 发送开发者配置文件令牌。 将分发和开发应用程序令牌分开。如果您尝试将沙盒令牌发送到 LIVE APNS 或反之亦然,这可能会导致错误。

为此苦苦挣扎了一段时间。对于我的情况,结果是:

a) 和过期的 APNS 证书。只有很小一部分错误解释说这是一个过期的证书。大多数是“对等方重置连接”。

b) 损坏的 APNS 证书。只有在重新生成证书后它才开始工作。在那之前,我再次遇到臭名昭著的“对等方重置连接”。