C # push information to APNs,

Source: Internet
Author: User

C # push information to APNs,
Implementation and Discussion of iPhone message push mechanism
Class Program {public static DateTime? Expiration {get; set;} public static readonly DateTime DoNotStore = DateTime. minValue; private static readonly DateTime UNIX_EPOCH = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind. utc); private static string DeviceToken = "token"; public const int DEVICE_TOKEN_BINARY_SIZE = 32; public const int DEVICE_TOKEN_STRING_SIZE = 64; public const Int MAX_PAYLOAD_SIZE = 256; private static X509Certificate certificate; private static X509CertificateCollection certificates; static void Main (string [] args) {string hostIP = "success"; // int port = 2195; string password = "ankejiaoyu"; // string certificatepath = "aps_developer_identity.p12"; // bin/debug string p12Filename = System. IO. path. combine (AppDomain. currentDomain. B AseDirectory, certificatepath); certificate = new X509Certificate2 (System. IO. file. readAllBytes (p12Filename), password, X509KeyStorageFlags. machineKeySet | X509KeyStorageFlags. persistKeySet | X509KeyStorageFlags. exportable); certificates = new X509CertificateCollection (); certificates. add (certificate); TcpClient apnsClient = new TcpClient (); apnsClient. connect (hostIP, port); SslStream apnsStream = New SslStream (apnsClient. getStream (), false, new RemoteCertificateValidationCallback (validateServerCertificate), new LocalCertificateSelectionCallback (selectLocalCertificate); try {// APNs does not support SSL 3.0 apnsStream. authenticateAsClient (hostIP, certificates, System. security. authentication. sslProtocols. tls, false);} catch (System. security. authentication. authenticationException ex) {Console. writeLine ("Error +" + ex. Message);} if (! ApnsStream. IsMutuallyAuthenticated) {Console. WriteLine ("error: Ssl Stream Failed to Authenticate! ");} If (! ApnsStream. CanWrite) {Console. WriteLine ("error: Ssl Stream is not Writable! ");} Byte [] message = ToBytes (); apnsStream. write (message);} public static byte [] ToBytes () {// Without reading the response which wocould make any identifier useful, it seems silly to // expose the value in the object model, although that wocould be easy enough to do. for // now we'll just use zero. int identifier = 0; byte [] identifierBytes = BitConverter. getBytes (IPAddress. hostToNetworkOrder (iden Tifier); // APNS will not store-and-forward a notification with no expiry, so set it one year in the future // if the client does not provide it. int expiryTimeStamp =-1; // Expiration time stamp if (Expiration! = DoNotStore) {// DateTime concreteExpireDateUtc = (Expiration ?? DateTime. UtcNow. AddMonths (1). ToUniversalTime (); DateTime concreteExpireDateUtc = (Expiration ?? DateTime. utcNow. addSeconds (20 )). toUniversalTime (); TimeSpan epochTimeSpan = concreteExpireDateUtc-UNIX_EPOCH; expiryTimeStamp = (int) epochTimeSpan. totalSeconds;} byte [] expiry = BitConverter. getBytes (IPAddress. hostToNetworkOrder (expiryTimeStamp); byte [] deviceToken = new byte [DeviceToken. length/2]; for (int I = 0; I <deviceToken. length; I ++) deviceToken [I] = byte. parse (DeviceToken. substring (I * 2, 2), System. Globalization. NumberStyles. HexNumber); if (deviceToken. Length! = DEVICE_TOKEN_BINARY_SIZE) {Console. WriteLine ("Device token length error! ");} Byte [] deviceTokenSize = BitConverter. getBytes (IPAddress. hostToNetworkOrder (Convert. toInt16 (deviceToken. length); string str = "{\" aps \ ": {\" alert \ ": \" this is the test message !! \ ", \" Badge \ ": 1, \" sound \ ": \" ankeapps\ "}"; byte [] payload = Encoding. UTF8.GetBytes (str); byte [] payloadSize = BitConverter. getBytes (IPAddress. hostToNetworkOrder (Convert. toInt16 (payload. length); List <byte []> icationicationparts = new List <byte []> (); // 1 Command notificationParts. add (new byte [] {0x01}); // Enhanced notification format command icationicationparts. add (identifierBytes); icationicationparts. add (expiry); icationicationparts. add (deviceTokenSize); icationicationparts. add (deviceToken); icationicationparts. add (payloadSize); icationicationparts. add (payload); return BuildBufferFrom (icationicationparts);} private static byte [] BuildBufferFrom (IList <byte []> bufferParts) {int bufferSize = 0; for (int I = 0; I <bufferParts. count; I ++) bufferSize + = bufferParts [I]. length; byte [] buffer = new byte [bufferSize]; int position = 0; for (int I = 0; I <bufferParts. count; I ++) {byte [] part = bufferParts [I]; Buffer. blockCopy (bufferParts [I], 0, buffer, position, part. length); position + = part. length;} return buffer;} private static bool validateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) {return true; // Dont care about server's cert} private static ‑selectlocalcertificate (object sender, string targetHost, using localCertificates, using remoteCertificate, string [] acceptableIssuers) {return certificate ;}

}

From Weizhi note (Wiz)



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.