我正在創建一個web api應用程序,並且我想向iOS設備發送通知。如何使用C#從APNS獲得通知響應
我試過用pushsharp,但它工作正常,只有很少的設備,而發送到多個設備與過期/無效令牌它不發送通知到所有設備。
所以,我用下面的代碼去:
public async Task pushMessage(string deviceToken, string message)
{
int port = 2195;
String hostname = "gateway.sandbox.push.apple.com";
String certificatePath = "~/test.p12" // my certificate path
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), CommonSource.GetAppleCertificatePassword(), X509KeyStorageFlags.MachineKeySet);
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, false);
MemoryStream memoryStream = new MemoryStream();
BinaryWriter writer = new BinaryWriter(memoryStream);
writer.Write((byte)0);
writer.Write((byte)0);
writer.Write((byte)32);
writer.Write(HexStringToByteArray(deviceToken.ToUpper()));
String payload = message.ToString();
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();
// Read message from the server.
//byte[] response = ReadMessage(sslStream);
client.Close();
}
catch (System.Security.Authentication.AuthenticationException ex)
{
LogError(ex.Message);
client.Close();
}
catch (Exception e)
{
LogError(e.Message);
client.Close();
}
}
此代碼的工作正是我想要的。
但現在我想檢查來自APNS服務器的響應。所以我用byte[] response = ReadMessage(sslStream);
檢查,ReadMessage方法是這樣的:
private byte[] ReadMessage(SslStream sslStream)
{
MemoryStream ms = new MemoryStream();
byte[] buffer = new byte[1024];
int bytes = -1;
do
{
bytes = sslStream.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, bytes);
} while (bytes != 0);
return ms.ToArray();
}
但是當我運行它,它停留在bytes = sslStream.Read(buffer, 0, buffer.Length);
我不能找出問題。
誰能告訴我,我的代碼有什麼問題?
將OnNotificationFailed事件處理程序附加到PushSharp對象。 如果通知失敗並且您可以記錄相關錯誤,它將被擊中。 – Ajay
@Ajay:正如我在問題中提到的那樣,在這個問題中,我並沒有使用PushSharp。我的問題是關於從蘋果服務器獲取響應。儘管我已經嘗試過,它給了我一個無效令牌的錯誤,並且它已經停止隊列。 –
@HinaKhuman重新下載您的證書和您的證書是無效的。我想, –