using
System;
using
System.Collections.Generic;
using
System.IO;
using
System.Linq;
using
System.Net.Security;
using
System.Net.Sockets;
using
System.Security.Authentication;
using
System.Security.Cryptography.X509Certificates;
using
System.Text;
using
System.Threading.Tasks;
namespace
ConsoleApplication1
{
class
Program
{
static
void
Main(
string
[] args)
{
while
(
true
)
{
pushMessage(Console.ReadLine());
}
}
public
static
void
pushMessage(
string
content)
{
string
deviceID =
"deviceToken替换掉这里"
;
int
port = 2195;
var
hostname =
"gateway.sandbox.push.apple.com"
;
var
certificatePath =
@"还记得.p12的证书文件吗?替换这里"
;
X509Certificate2 clientCertificate =
new
X509Certificate2(System.IO.File.ReadAllBytes(certificatePath),
"还记得证书密码吗?你设定的,替换这里"
);
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(deviceID.ToUpper()));
String payload =
"{\"aps\":{\"alert\":\""
+ content +
"\",\"badge\":10,\"sound\":\"default\"}}"
;
var
payloadlength = System.Text.Encoding.UTF8.GetBytes(payload).Length;
writer.Write((
byte
)0);
writer.Write((
byte
)payloadlength);
byte
[] b1 = System.Text.Encoding.UTF8.GetBytes(payload);
writer.Write(b1);
writer.Flush();
byte
[] array = memoryStream.ToArray();
sslStream.Write(array);
sslStream.Flush();
client.Close();
}
catch
(System.Security.Authentication.AuthenticationException ex)
{
client.Close();
}
catch
(Exception e)
{
client.Close();
}
}
private
static
bool
ValidateServerCertificate(
object
sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
Console.WriteLine(certificate.Subject);
return
true
;
}
public
static
byte
[] HexStringToByteArray(
string
hex)
{
return
Enumerable.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
}
}