Click here to Skip to main content
15,889,909 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am trying to push notification in iOS every time i am getting "Authentication failed because the remote party has closed the transport stream." error.

What I have tried:

i am trying below Code:

C#
public  void pushMessage(string deviceID)
       {
           int port = 2195;
           string hostname = "gateway.sandbox.push.apple.com";
         //  String hostname = "gateway.push.apple.com";
           String certificatePath = Server.MapPath("push.pem");
           X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "****1234");
           X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);

           TcpClient client = new TcpClient(hostname, port);
           SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null);

           try
           {
              // client.Connect(hostname,port);
               //sslStream.AuthenticateAsServer(hostname, certificatesCollection, SslProtocols.Default, true);
               ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
               sslStream.AuthenticateAsServer(clientCertificate, false, SslProtocols.Ssl3, true);
               MemoryStream memoryStream = new MemoryStream();
               BinaryWriter writer = new BinaryWriter(memoryStream);
               writer.Write((byte)0);
               writer.Write((byte)0);
               writer.Write((byte)32);

               writer.Write(ConvertToByteArray(deviceID));
               String payload = "{\"aps\":{\"alert\":\"" + "Hi,, This Is a Sample Push Notification For IPhone.." + "\",\"badge\":1,\"sound\":\"default\"}}";
               writer.Write((byte)0);
               writer.Write((byte)payload.Length);
               byte[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
               writer.Write(b1);
               writer.Flush();
               byte[] array = memoryStream.ToArray();
               sslStream.Write(array);
               sslStream.Flush();
               client.Close();
           }
           catch (System.Security.Authentication.AuthenticationException ex)
           {
               client.Close();
           }
           catch (Exception e)
           {
               client.Close();
           }
       }


       public static byte[] ConvertToByteArray(string value)
       {
           byte[] bytes = null;
           if (String.IsNullOrEmpty(value))
               bytes = null;
           else
           {
               int string_length = value.Length;
               int character_index = (value.StartsWith("0x", StringComparison.Ordinal)) ? 2 : 0; // Does the string define leading HEX indicator '0x'. Adjust starting index accordingly.
               int number_of_characters = string_length - character_index;

               bool add_leading_zero = false;
               if (0 != (number_of_characters % 2))
               {
                   add_leading_zero = true;

                   number_of_characters += 1;  // Leading '0' has been striped from the string presentation.
               }

               bytes = new byte[number_of_characters / 2]; // Initialize our byte array to hold the converted string.

               int write_index = 0;
               if (add_leading_zero)
               {
                   bytes[write_index++] = FromCharacterToByte(value[character_index], character_index);
                   character_index += 1;
               }

               for (int read_index = character_index; read_index < value.Length; read_index += 2)
               {
                   byte upper = FromCharacterToByte(value[read_index], read_index, 4);
                   byte lower = FromCharacterToByte(value[read_index + 1], read_index + 1);

                   bytes[write_index++] = (byte)(upper | lower);
               }
           }

           return bytes;
       }

       private static byte FromCharacterToByte(char character, int index, int shift = 0)
       {
           byte value = (byte)character;
           if (((0x40 < value) && (0x47 > value)) || ((0x60 < value) && (0x67 > value)))
           {
               if (0x40 == (0x40 & value))
               {
                   if (0x20 == (0x20 & value))
                       value = (byte)(((value + 0xA) - 0x61) << shift);
                   else
                       value = (byte)(((value + 0xA) - 0x41) << shift);
               }
           }
           else if ((0x29 < value) && (0x40 > value))
               value = (byte)((value - 0x30) << shift);
           else
               throw new InvalidOperationException(String.Format("Character '{0}' at index '{1}' is not valid alphanumeric character.", character, index));

           return value;
       }


       public static bool ValidateServerCertificate(
          object sender,
          X509Certificate certificate,
          X509Chain chain,
          SslPolicyErrors sslPolicyErrors)
       {
           if (sslPolicyErrors == SslPolicyErrors.None)
               return true;

           Console.WriteLine("Certificate error: {0}", sslPolicyErrors);

           // Do not allow this client to communicate with unauthenticated servers.
           return false;
       }

       private byte[] HexString2Bytes(String hexString)
       {
           //check for null
           if (hexString == null) return null;
           //get length
           int len = hexString.Length;
           if (len % 2 == 1) return null;
           int len_half = len / 2;
           //create a byte array
           byte[] bs = new byte[len_half];
           try
           {
               //convert the hexstring to bytes
               for (int i = 0; i != len_half; i++)
               {
                   bs[i] = (byte)Int32.Parse(hexString.Substring(i * 2, 2), System.Globalization.NumberStyles.HexNumber);
               }
           }
           catch (Exception ex)
           {
               //MessageBox.Show("Exception : " + ex.Message);
           }
           //return the byte array
           return bs;
       }






Please help me..
I checked the certificate it works perfectly in php code.
Posted
Updated 10-Mar-16 0:53am
v2
Comments
[no name] 10-Mar-16 10:43am    
Help me please.
shweta2005mca 13-Dec-17 15:24pm    
HI did you get the answer i am facing the similar issue but with Non English Push Notification.

I have used below code for payload, which is working fine for English but for non English it shows me Unicode characters in Notification
/**/
writer.Write((byte)2); // The command (version 2)
// 4 bytes for the frameLength (this includes all the items ids listed below)
int frameLength = 1 + 2 + 32 + 1 + 2 + payload.Length; // (tokenCommand + tokenLength + token) + (payloadCommand + payloadLength + payload)
this.writeIntBytesAsBigEndian(writer, frameLength, 4);

// DEVICE ID
writer.Write((byte)1); // Command for Item ID: deviceId
byte[] tokenBytes = this.HexStringToByteArray(deviceToken.ToUpper());
this.writeIntBytesAsBigEndian(writer, tokenBytes.Length, 2);
writer.Write(tokenBytes);

// PAYLOAD
writer.Write((byte)2); // Command for Item ID: payload
this.writeIntBytesAsBigEndian(writer, payload.Length, 2);

writer.Write(System.Text.Encoding.UTF8.GetBytes(payload), 0, System.Text.Encoding.UTF8.GetBytes(payload).Length);


Thanks.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900