【问题标题】:Apple Push Notifications (APN) service server side Python 2 script in iOSiOS 中的 Apple Push Notifications (APN) 服务服务器端 Python 2 脚本
【发布时间】:2015-02-07 09:13:59
【问题描述】:

我已将我的 iOS 应用程序配置为启用了 Apple 推送通知 (APN) 服务。我能够使用 PHP 和 Python 3 脚本向设备发送通知。我用本地机器在本地服务器上进行了测试。但是现在我需要用 Python2 编写脚本。

下面是我编写的脚本,当我运行它时,我什么也得不到。既没有通知我的设备,也没有命令行错误。

import socket, ssl, json, struct
import binascii
import os

deviceToken = 'my_device_tocken_without_spaces' 

thePayLoad = {
     'aps': {
          'alert':'My first push notification!',
          'sound':'default'
          }
     }

theCertfile = 'ck3_2.pem'

theHost = ( 'gateway.sandbox.push.apple.com', 2195 )

data = json.dumps( thePayLoad )

theFormat = '!BH32sH%ds' % len(data)

theNotification = struct.pack( theFormat, 0, 32, deviceToken, len(data), data )

ssl_sock = ssl.wrap_socket( socket.socket( socket.AF_INET, socket.SOCK_STREAM ), certfile = theCertfile )

ssl_sock.connect( theHost )

ssl_sock.write( theNotification )

ssl_sock.close()

我错过了什么?如何检查错误发生在哪里?

我使用 XAMPP 在 localhost 中运行 PHP 脚本,并在命令行中运行 Python 脚本,因为我无法使用 XAMPP 设置 Python,我已经发布了一个问题 here

【问题讨论】:

    标签: ios sockets python-2.7 localhost apple-push-notifications


    【解决方案1】:

    你可以考虑https://github.com/djacobs/PyAPNs,它包含了很多有用的功能,包括:

    • 错误处理
    • 支持增强的消息格式和在错误响应之前发送的自动重发消息
    • 具有出色性能的非阻塞 ssl 套接字连接

    【讨论】:

      【解决方案2】:

      我认为您的代码没有问题。您可以尝试在ssl_sock.connect( theHost )之后添加以下行

      print repr(ssl_sock.getpeername())
      print ssl_sock.cipher()
      print pprint.pformat(ssl_sock.getpeercert())
      

      这将打印有关您的连接的 ssl 的信息。

      或者,您可以创建一个示例服务器并更改客户端中的连接并针对服务器进行测试。 http://carlo-hamalainen.net/blog/2013/1/24/python-ssl-socket-echo-test-with-self-signed-certificate

      【讨论】:

      • 是的,你是对的。代码几乎是正确的,它在远程服务器内部运行,而不是本地计算机。无论如何,尝试在本地机器上运行时出现的错误是 File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 333, in connect self._real_connect(addr, False) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ssl.py", line 314, in _real_connect self.ca_certs, self.ciphers) ssl.SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib
      • 您的证书文件路径是否正确?或有访问权限?我发现了类似的错误stackoverflow.com/a/6806097/625144
      【解决方案3】:

      您导入了 binascii,但忘记使用它。 将 token 和 json 数据转换为字节数组,例如:

      deviceToken = binascii.a2b_hex('my_device_tocken_without_spaces')
      

      data = json.dumps(thePayLoad, separators=(',', ':'), ensure_ascii=False).encode('utf-8')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-15
        • 1970-01-01
        • 2014-07-17
        • 2015-10-29
        • 2021-04-18
        • 1970-01-01
        • 2016-06-09
        • 1970-01-01
        相关资源
        最近更新 更多