IT정보사전

[.Net] Apple Push Notification 보내기 본문

웹 프로그래밍

[.Net] Apple Push Notification 보내기

작은나무0530 2018. 12. 8. 22:48
728x90
반응형

안녕하세요~ 작은나무입니다!!

모바일 iOS 앱을 만들어서 배포하던 중에 웹 관리자가 Push Notification을 보내기 위해 아래와 같은 소스를 작성하였습니다. 

void Push_Message(string HostName, int Port, string certificatePath, string certPassword, string PushNumber, string Message, int BadgeNo)
{
    X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath),
    certPassword, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet |X509KeyStorageFlags.Exportable);
    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 (AuthenticationException aex)
    {
        client.Close();
        return;
    }
    catch (System.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 = PushNumber;
    writer.Write(HexStringToByteArray(deviceID.ToUpper()));
    int Badge = BadgeNo + 1;
    String payload = "{"aps":{"alert":"" + GetEncodeMsg(Message) + "","badge":" + Badge + ","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 = 0i <s.Lengthi += 2)
    {
        buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
    }
    return buffer;
}

//한글깨짐 방지를 위해 Message를 Encoding합니다.
public static string GetEncodeMsg(string alertMsg)
{
    alertMsg = alertMsg.Replace(""", """);
    System.Text.StringBuilder encodedString = new System.Text.StringBuilder();

    foreach (char c in alertMsg)
    {
        if ((int)c <32 || (int)c >127)
            encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c)));
        else
            encodedString.Append(c);
    }

    return encodedString.ToString();
}

728x90
반응형
그리드형
Comments