当前位置: 移动技术网 > IT编程>开发语言>c# > C#推送信息到APNs的方法

C#推送信息到APNs的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了c#推送信息到apns的方法。分享给大家供大家参考。具体实现方法如下:

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 = "273eeddaef02192cf4ba5b666453b258f2d2a1ad02f549105fd03fea789d809d";
  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 = "gateway.sandbox.push.apple.com";//
   int port = 2195;
   string password = "ankejiaoyu";//
   string certificatepath = "aps_developer_identity.p12";//bin/debug
   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));
   try
   {
    //apns已不支持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 would make any identifier useful, it seems silly to
   // expose the value in the object model, although that would be easy enough to do. for
   // now we'll just use zero.
   int identifier = 0;
   byte[] identifierbytes = bitconverter.getbytes(ipaddress.hosttonetworkorder(identifier));
   // 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;//过期时间戳
   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\":\"这是测试消息!!\",\"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, sslpolicyerrors sslpolicyerrors)
  {
   return true; // dont care about server's cert
  }
  private static x509certificate selectlocalcertificate(object sender, string targethost, x509certificatecollection localcertificates,
   x509certificate remotecertificate, string[] acceptableissuers)
  {
   return certificate;
  }
}

希望本文所述对大家的c#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网