我是.net的新手,正在使用C#进行APN服务器端开发。我正在使用以下代码将消息推送到苹果服务器。
private void pushMessage()
{
int port = 2195;
String deviceID = "4564c705 63b371aa 3811699e 1e4ac3d2 ba592b27 f2a5a613 d25cd035 xx213e54";
String hostname = "gateway.sandbox.push.apple.com"; // TEST
//String hostname = "gateway.push.apple.com"; // REAL
// @"cert.p12";
String certificatePath = HttpContext.Current.Server.MapPath("Certi.p12");
//X509Certificate2 clientCertificate = new X509Certificate2(certificatePath, "");
X509Certificate2 clientCertificate = new X509Certificate2(System.IO.File.ReadAllBytes(certificatePath), "", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.Exportable);
X509Certificate2Collection certificatesCollection = new X509Certificate2Collection(clientCertificate);
TcpClient client = new TcpClient(hostname, port);
// _apnsStream = new SslStream(_apnsClient.GetStream(), false, validateServerCertificate, SelectLocalCertificate);
//SslStream sslStream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate),null);
SslStream sslStream = new SslStream(client.GetStream(), false, validateServerCertificate, SelectLocalCertificate);
try
{
sslStream.AuthenticateAsClient(hostname, certificatesCollection, SslProtocols.Default, false);
}
catch (Exception e)
{
throw (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)
writer.Write(HexStringToByteArray(deviceID.ToUpper()));
String payload = "{\"aps\":{\"alert\":\"hello\",\"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();
}
private string HexStringToByteArray(string p)
{
throw new NotImplementedException();
}
在执行过程中,出现了“调用SSPI失败,请参见内部异常”的错误。
我做错了什么或者遗漏了什么?在Windows上需要安装任何证书吗?请帮助我。
查看详情...
并告诉我们内部异常的详细信息。你的代码也有一些问题 - 比如你的catch
是无用的 - 它只会丢失你的堆栈跟踪和任何在throw(e)
后的代码都不会被执行 (仅举几个问题)。 - Daniel Kelleythrow(e);
会立即从异常处理程序中退出,所以下面的两行代码永远不会被执行,异常将会一直向上冒泡。 - Thorsten Dittmar