Get the failed push token from the feedback server of Apple apns, apnsfeedback

Source: Internet
Author: User

Get the failed push token from the feedback server of Apple apns, apnsfeedback

When developing your own apple PUSH Service, you must properly control the tokens of ios devices. This Token is generated by the Apns server on the Apple Server, that is, every time the app asks Apns for tokens, the tokens generated by the Apple Server are recorded in Apns. We need to develop device message pushing Based on the Token. All tokens need to be recorded and managed by ourselves, each device corresponds to a unique Token, and the app user logon will have an alias bound to the tokne. In this way, the corresponding Token can be found for pushing by the alias, then push to this iso device. For invalid tokens, We need to access Apple's feedbackServer to retrieve invalid tokens, and then remove the invalid tokens of local records.

Note:
1. we recommend that you establish a persistent connection with the feedback server. If the connection is too frequent, it may be used as an attack (it does not matter when testing is simple). After the actual development is complete, basically, we can establish a socket connection with the feedback server half a day to retrieve invalid tokens,
2. The obtained token is added with the feedback service when the last push failed to your application. The specific time of the failure will be returned.
3. The returned data is composed of three parts. See the figure below:

The configuration contains three parts: The first part is the timestamp of the last push failure, the second part is the length of device_token, and the third part is the invalid device_token.

Paste the code for connecting to feedback in PushSharp.

1 /// <summary> 2 /// FeedbackService 3 /// </summary> 4 public class FeedbackService 5 {6 public FeedbackService (ApnsConfiguration configuration Configuration) 7 {8 configuration = configuration; 9} 10 11 public ApnsConfiguration Configuration {get; private set;} 12 13 public delegate void FeedbackReceivedDelegate (string deviceToken, DateTime timestamp); 14 public event FeedbackReceivedDelegate FeedbackRec Eived; 15 16 public void Check () 17 {18 var encoding = Encoding. ASCII; 19 20 var certificate = Configuration. certificate; 21 22 var certificates = new X509CertificateCollection (); 23 certificates. add (certificate); 24 25 var client = new TcpClient (Configuration. feedbackHost, Configuration. feedbackPort); 26 27 var stream = new SslStream (client. getStream (), true, 28 (sender, cert, chain, sslErrs) => {Return true;}, 29 (sender, targetHost, localCerts, remoteCert, acceptableIssuers) =>{ return certificate;}); 30 31 stream. authenticateAsClient (Configuration. feedbackHost, certificates, System. security. authentication. sslProtocols. tls, false); 32 33 34 // Set up 35 byte [] buffer = new byte [4096]; 36 int recd = 0; 37 var data = new List <byte> (); 38 39 // Get the first feedback 40 recd = stream. re Ad (buffer, 0, buffer. length); 41 42 // Continue while we have results and are not disposing 43 while (recd> 0) 44 {45 // Add the same ed data to a list buffer to work with (easier to manipulate) 46 for (int I = 0; I <recd; I ++) 47 data. add (buffer [I]); 48 49 // Process each complete notification "packet" available in the buffer 50 while (data. count> = (4 + 2 + 32) // Minimum size for a valid pac Ket 51 {52 var secondsBuffer = data. getRange (0, 4 ). toArray (); 53 var tokenLengthBuffer = data. getRange (4, 2 ). toArray (); 54 55 // Get our seconds since epoch 56 // Check endianness and reverse if needed 57 if (BitConverter. isLittleEndian) 58 Array. reverse (secondsBuffer); 59 var seconds = BitConverter. toInt32 (secondsBuffer, 0); 60 61 // Add seconds since 1970 to that date, in UTC 62 var timestamp = New DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind. utc ). addSeconds (seconds); 63 64 // flag to allow feedback times in UTC or local, but default is local 65 if (! Configuration. feedbackTimeIsUTC) 66 timestamp = timestamp. toLocalTime (); 67 68 69 if (BitConverter. isLittleEndian) 70 Array. reverse (tokenLengthBuffer); 71 var tokenLength = BitConverter. toInt16 (tokenLengthBuffer, 0); 72 73 if (data. count> = 4 + 2 + tokenLength) 74 {75 76 var tokenBuffer = data. getRange (6, tokenLength ). toArray (); 77 // Strings shouldn't care about endian-ness... this shouldn't be r Eversed 78 // if (BitConverter. isLittleEndian) 79 // Array. reverse (tokenBuffer); 80 var token = BitConverter. toString (tokenBuffer ). replace ("-",""). toLower (). trim (); 81 82 // Remove what we parsed from the buffer 83 data. removeRange (0, 4 + 2 + tokenLength); 84 85 // Raise the event to the consumer 86 var evt = FeedbackReceived; 87 if (evt! = Null) 88 evt (token, timestamp); 89} 90 else 91 {92 continue; 93} 94 95} 96 97 // Read the next feedback 98 recd = stream. read (buffer, 0, buffer. length); 99} 100 101 try102 {103 stream. close (); 104 stream. dispose (); 105} 106 catch {} 107 108 try109 {110 client. client. shutdown (SocketShutdown. both); 111 client. client. dispose (); 112} 113 catch {} 114 try {client. close ();} 116 catch {} 117} 118}View Code

The processing logic is as follows:

1 /// <summary> 2 // process invalid Token logic information 3 /// </summary> 4 public class TokenProvider 5 {6 private FeedbackService fs = null; 7 private int hour = 12; 8 private string CID; 9 10 public TokenProvider (ApnsConfiguration cf, string CID) 11 {12 this. fs = new FeedbackService (cf); 13 this. CID = CID; 14 try15 {16 int hour = int. parse (ConfigurationManager. appSettings ["ManagerTokenHour"]); // Token control time 17} 18 Catch {hour = 12 ;} 19} 20 21 // <summary> 22 // enable Token logic information for processing invalidation 23 // </summary> 24 // <param name = "cf"> </param> 25 public void Init () 26 {27 try28 {29 Thread thsub = new Thread (new ThreadStart () => 30 {31 while (true) 32 {33 try34 {35 fs. check (); 36} 37 catch (Exception ex) 38 {39 LogInfoProvider. config. logs. add (new LogClass () {LogStr = "fs. check () Error! CID = "+ CID, ExInfo = ex}); 40} 41 Thread. sleep (hour * 60*60*1000); 42} 43}); 44 fs. feedbackReceived + = fs_FeedbackReceived; 45 thsub. start (); 46 LogInfoProvider. config. logs. add (new LogClass () {LogStr = "Open TokenProvider! CID = "+ CID}); 47} 48 catch (Exception ex) 49 {LogInfoProvider. config. Logs. Add (new LogClass () {LogStr =" Open TokenProvider Error! CID = "+ CID, ExInfo = ex });} 50} 51 52 // <summary> 53 // process invalid Token information 54 // </summary> 55 // <param name = "deviceToken"> </param> 56 // <param name = "timestamp"> </param> 57 private void fs_FeedbackReceived (string deviceToken, dateTime timestamp) 58 {59 try60 {61 p_DeleteToken p = new p_DeleteToken (deviceToken); 62 if (p. executionDelete () {63 LogInfoProvider. config. logs. add (new LogClass () {LogStr = "Delete lose token success>" + deviceToken}); 64} else {65 LogInfoProvider. config. logs. add (new LogClass () {LogStr = "Delete lose token error>" + deviceToken, ExInfo = null}); 66}; 67} 68 catch (Exception ex) 69 {70 LogInfoProvider. config. logs. add (new LogClass () {LogStr = "fs_FeedbackReceived Error! CID = "+ CID, ExInfo = ex}); 71} 72} 73}View Code

 

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.