我正在为iPhone构建一个客户端 - 服务器应用程序,服务器是用c#编写的,并使用TcpListener监听传入的连接,并使用TcpClient来处理每个连接。 代码看起来像这样:
private void startAcceptingConnections()
{
m_Listener = new TcpListener(i_IPAddress, i_Port);
m_Listener.Start();
while (true)
{
//blocking
TcpClient tcpConnection = m_Listener.AcceptTcpClient();
Thread ClientAuthenticationThread = new Thread(new ParameterizedThreadStart(HandleClientConnection));
ClientAuthenticationThread.Start(tcpConnection);
}
}
private void HandleClientConnection(object i_Client)
{
TcpClient client = i_Client as TcpClient;
if (client != null)
{
NetworkStream clientStream = client.GetStream();
byte[] buffer = new byte[4096];
int bytesRead = 0;
//blocking
bytesRead = clientStream.Read(buffer, 0, 4096);
if (bytesRead == 0)
{
client.Close();
}
else
{
// do something with bytesRead
}
}
}
我想在我的应用中添加SSL,所以这就是我到目前为止所做的:
现在我知道我需要在我的服务器上安装此文件,但我不知道如何。 有人可以指导我吗?
@@@@@ 我在MSDN中找到了这个代码,是否需要添加以支持SSL?
private void startAcceptingConnections()
{
string certPath = "C:\\...Path...\\ServerCertificates.p12";
serverCertificate = new X509Certificate(certPath, "serverCertPassword");
m_Listener = new TcpListener(i_IPAddress, i_Port);
m_Listener.Start();
while (true)
{
//blocking
TcpClient tcpConnection = m_Listener.AcceptTcpClient();
Thread ClientAuthenticationThread = new Thread(new ParameterizedThreadStart(HandleClientConnection));
ClientAuthenticationThread.Start(tcpConnection);
}
}
private void HandleClientConnection(object i_Client)
{
TcpClient client = i_Client as TcpClient;
try
{
NetworkStream clientStream = client.GetStream();
// A client has connected. Create the
// SslStream using the client's network stream.
SslStream sslStream = new SslStream(clientStream, false);
sslStream.AuthenticateAsServer(serverCertificate, false, SslProtocols.Tls, true);
byte[] buffer = new byte[4096];
int bytesRead = 0;
//blocking
bytesRead = clientStream.Read(buffer, 0, 4096);
if (bytesRead == 0)
{
sslStream.Close();
client.Close();
}
else
{
// do something with bytesRead
}
}
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.");
sslStream.Close();
client.Close();
return;
}
}