ios push(python编程)

原理参考:http://blog.csdn.net/bytxl/article/details/16982083

上代码:

import socket, ssl, pprint, binascii

maxPayloadLength = 256
deviceTokenLength = 32

def normal_payload(soundValue, badgeValue, alertstr):
    """
    Build all notifications items to one string.
    """
    keys = []
    apsKeys = []
    if soundValue:
        apsKeys.append('"sound":"%s"' % soundValue)

    if badgeValue:
        apsKeys.append('"badge":%d' % int(badgeValue))

    if alertstr != None:
        alertArgument = ""
        if isinstance(alertstr, str):
            alertArgument = alertstr
            apsKeys.append('"alert":"%s"' % alertArgument)
        else:
            print "alertstr is not str"
            return

    keys.append('"aps":{%s}' % ",".join(apsKeys))
    payload = "{%s}" % ",".join(keys)

    if len(payload) > maxPayloadLength:
        raise APNSPayloadLengthError, "Length of Payload more than %d bytes." % maxPayloadLength

    return payload

def Hex2Bin(hexToken):
    """
    Add deviceToken as a hexToken
    Strips out whitespace and <>
    """
    hexToken = hexToken.strip().strip('<>').replace(' ','').replace('-', '')
    deviceTokenBin = binascii.unhexlify(hexToken)

    return deviceTokenBin

def main():
    clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print( "socket create success" )
    ssl_sock = ssl.wrap_socket( clientsock, keyfile = "aps_development_unencrypted.key", 
        certfile = "aps_development.pem" )
    ssl_sock.connect(('gateway.sandbox.push.apple.com', 2195))
    print( "socket connect success" )
    pprint.pprint(ssl_sock.getpeercert())

    # create push package
    payload = normal_payload( "default", 1, "python ios push test" )
    payloadLength = len(payload)
    deviceToken = "ee03ee86 c6c57219 d167d06f 1fae87b0 9e857a2d 635ffacc 71046f4e 1974594f"
    deviceTokenBin = Hex2Bin( deviceToken )
    
    msg = chr(0) + chr(0) + chr(32) + deviceTokenBin + chr(0) + chr(payloadLength) + payload

    ssl_sock.send( msg )
    print "msg send: %s" % repr( msg )
    ssl_sock.close()
    
main()


你可能感兴趣的:(ios push(python编程))