簡體   English   中英

iOS中的Apple推送通知(APN)服務服務器端Python 2腳本

[英]Apple Push Notifications (APN) service server side Python 2 script in iOS

我已經為我的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,我已在此處發布了一個問題。

您可以考慮包含許多有用功能的https://github.com/djacobs/PyAPNs ,包括:

  • 錯誤處理
  • 支持增強的消息格式並自動重新發送在錯誤響應之前發送的消息
  • 非阻塞ssl套接字連接,性能卓越

我認為您的代碼沒有任何問題。 您可以嘗試在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

你導入了binascii,但你忘了使用它。 將token和json數據轉換為字節數組,例如:

deviceToken = binascii.a2b_hex('my_device_tocken_without_spaces')

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM