【发布时间】:2018-01-08 00:47:43
【问题描述】:
我正在创建一个 web api 应用程序,我想向 iOS 设备发送通知。
我已尝试使用 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:正如我在问题中提到的,在这个问题中我并没有使用 PushSharp。我的问题是关于从苹果服务器获得响应。虽然我已经尝试过,但它给了我一个无效令牌的错误并且它已经停止了队列。
-
@HinaKhuman 重新下载您的证书,您的证书无效。我认为,
-
@JagadeeshGovindaraj:是的,我也试过了,但我收到了同样的错误。
-
@HinaKhuman.my 简单的答案是您的令牌从移动客户端无效。使用 FCM 对于 pushnotification.google 有不错的控制台向设备发送推送通知。
标签: c# ios push-notification apple-push-notifications