public class Appleapnsmessage {//<summary>///Apple Information Push certificate path (note Beta is not the same as the official release certificate)///</S ummary> private static string Cerpath = configurationmanager.appsettings["Cerpath"]; <summary>///Apple Push service Password///</summary> private static string msgpushpwd = Configurati onmanager.appsettings["Msgpushpwd"]; <summary>///Apple Push service Switch//open: Open close: Off//</summary> private static Strin G Msgpushswitch = configurationmanager.appsettings["Msgpushswitch"]; <summary>///Apple message push request address product version: gateway.push.apple.com test Environment: gateway.sandbox.push.apple.com//&L t;/summary> private static string ioshosturl = configurationmanager.appsettings["Ioshosturl"]; <summary>///Apple message push request port//</summary> private static string ioshostport = Configur ationmanager.appsettings["Ioshostport"]; 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); public static string devicetoken = "";//;//Apple device 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; public static string apnsmessage = "Test content!! "; <summary>///Send Message///</summary> public static void SendMessage () { Apple push switch if (Msgpushswitch = = "Close") {return; } string hostip = ioshosturl;//"gateway.push.apple.com";//"gateway.sandbox.push.apple.com";//int PO RT = Int. Parse (Ioshostport); String PAssWOrd = string. Empty; String Certificatepath = String. Empty; Password = msgpushpwd;//"123456"; Certificatepath = cerpath;//"RESOURCES\\PUSHCERUSE.P12"; String p12filename = System.IO.Path.Combine (AppDomain.CurrentDomain.BaseDirectory, 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)); The try {//apns already does not support SSL 3.0 Apnsstream.autHenticateasclient (HostIP, certificates, System.Security.Authentication.SslProtocols.Tls, false); } catch (System.Security.Authentication.AuthenticationException ex) {Console.writeli NE ("error+" + ex. Message); } if (!apnsstream.ismutuallyauthenticated) {Console.WriteLine ("Error:ssl Stream Fail Ed 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 would do any identifie R useful, it seems silly to//expose the value of the object model, although that would is easy enough to do. For//Now we'll just use zero. int identifier = 0; byte[] Identifierbytes = BiTconverter.getbytes (Ipaddress.hosttonetworkorder (identifier)); APNS won't store-and-forward a notification with no expiry, so set it one year of the future//if the CL Ient does not provide it. int expirytimestamp = -1;//expiration timestamp if (Expiration! = Donotstore) {//datetime concretee XPIREDATEUTC = (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 Err or! "); } byte[] Devicetokensize = Bitconverter.getbytes (Ipaddress.hosttonetworkorder (Convert.ToInt16 (deviceToken.Lengt h))); String str = "{\" aps\ ": {\" alert\ ": \" "+ Apnsmessage +" \ ", \" badge\ ": 1,\" sound\ ": \" anke.mp3\ "}}"; byte[] payload = Encoding.UTF8.GetBytes (str); byte[] payloadsize = Bitconverter.getbytes (Ipaddress.hosttonetworkorder (convert.toint16 (payload). Length))); list<byte[]> notificationparts = new list<byte[]> (); 1 Command notificationparts.add (new byte[] {0x01}); Enhanced Notification Format Command Notificationparts.add (identifierbytes); Notificationparts.add (expiry); Notificationparts.add (devicetokensize); Notificationparts.add (Devicetoken); Notificationparts.add (payloadsize); Notificationparts.add (payload); Return Buildbufferfrom (Notificationparts); } 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, Sslpol Icyerrors sslpolicyerrors) {return true;//Dont care about server ' s cert} private Stati C X509CertificateSelectlocalcertificate (object sender, String targethost, X509CertificateCollection localcertificates, x509certific Ate Remotecertificate, string[] acceptableissuers) {return certificate; } }
. NET C # Apple message Push tool class