C# iPhone 推送服务器?
-
20-08-2019 - |
题
我正在尝试用 C# 为 iPhone 编写一个推送服务器。我有以下代码:
// Create a TCP/IP client socket.
using (TcpClient client = new TcpClient())
{
client.Connect("gateway.sandbox.push.apple.com", 2195);
using (NetworkStream networkStream = client.GetStream())
{
Console.WriteLine("Client connected.");
X509Certificate clientCertificate = new X509Certificate(@"certfile.p12", passwordHere);
X509CertificateCollection clientCertificateCollection = new X509CertificateCollection(new X509Certificate[1] { clientCertificate });
// Create an SSL stream that will close the client's stream.
SslStream sslStream = new SslStream(
client.GetStream(),
false,
new RemoteCertificateValidationCallback(ValidateServerCertificate),
null
);
try
{
sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com");
}
catch (AuthenticationException e)
{
Console.WriteLine("Exception: {0}", e.Message);
if (e.InnerException != null)
{
Console.WriteLine("Inner exception: {0}", e.InnerException.Message);
}
Console.WriteLine("Authentication failed - closing the connection.");
client.Close();
return;
}
}
等等....
只有我不断收到异常:“对 SSPI 的调用失败,请参阅内部异常” 内部异常 ->“收到的消息出乎意料或格式不正确。
有谁知道这里出了什么问题吗?
解决方案
了它。替换sslStream.AuthenticateAsClient( “gateway.sandbox.push.apple.com”);与sslStream.AuthenticateAsClient( “gateway.sandbox.push.apple.com”,clientCertificateCollection,SslProtocols.Default,FALSE);并注册在PC上的证书。
编辑:下面是用于创建一个有效载荷的要求的代码:
private static byte[] GeneratePayload(byte [] deviceToken, string message, string sound)
{
MemoryStream memoryStream = new MemoryStream();
// Command
memoryStream.WriteByte(0);
byte[] tokenLength = BitConverter.GetBytes((Int16)32);
Array.Reverse(tokenLength);
// device token length
memoryStream.Write(tokenLength, 0, 2);
// Token
memoryStream.Write(deviceToken, 0, 32);
// String length
string apnMessage = string.Format ( "{{\"aps\":{{\"alert\":{{\"body\":\"{0}\",\"action-loc-key\":null}},\"sound\":\"{1}\"}}}}",
message,
sound);
byte [] apnMessageLength = BitConverter.GetBytes((Int16)apnMessage.Length);
Array.Reverse ( apnMessageLength );
// message length
memoryStream.Write(apnMessageLength, 0, 2);
// Write the message
memoryStream.Write(System.Text.ASCIIEncoding.ASCII.GetBytes(apnMessage), 0, apnMessage.Length);
return memoryStream.ToArray();
} // End of GeneratePayload
其他提示
从Zenox的评论: 使用不同版本的AuthenticateAsClient
sslStream.AuthenticateAsClient("gateway.sandbox.push.apple.com", clientCertificateCollection, SslProtocols.Default, false);
其他的方法是在即将使用X509Certificate2和X509CertificateCollection2类。
我最近用过 适用于 Windows 的咆哮 将消息推送到 Prowl 客户端 在 iPhone 上使用 .Net 代码. 。因此,您无需自己编写推送服务器即可获得功能。
“接收到的消息是意外或格式。”该错误通常是当你没有在Windows中注册的P12证书。 (在P12文件在Vista下,只需双击并导入向导将打开)
在我来说,我不得不从我的Windows 8中删除所有的证书,然后才能发送推送通知到苹果设备重新安装。
我不知道为什么我的证书停止工作,我正在寻找正确的原因,并很快将在这里更新。
不隶属于 StackOverflow