Apple Development Push Service 인증서와 private key를 함께 선택하여 P12 형식으로 Export 한다.

터미널을 실행시켜 다음과 같이 입력하여 P12 파일을 PEM 형태로 변경한다.

$ openssl pkcs12 -in cert.p12 -clcerts -out cert.pem

다음과 같은 C# 코드를 통해서 Push Message를 보낼 수 있다.

int port = 2195;
String hostname = "gateway.sandbox.push.apple.com";
String certificatePath = "cert.pem";

X509Certificate2 clientCertificate = new X509Certificate2(certificatePath);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);

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

try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Tls, true);
}
catch(Exception e)
{
client.Close();
return;
}

MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);  //The command
writer.Write((byte)0);  //The first byte of the deviceId length (big-endian first byte)
writer.Write((byte)32); //The deviceId length (big-endian second byte)

String deviceID = "00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000";
writer.Write(HexStringToByteArray(deviceID.ToUpper()));

String payload = "{\"aps\":{\"alert\":\"Push notification test\",\"badge\":0,\"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();

public static bool ValidateServerCertificate(Object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
}

public static byte[] HexStringToByteArray(String s)
{
s = s.Replace(" ", "");
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i < s.Length; i += 2)
{
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
}
return buffer;
}

Posted by NuBiFoRM :