在C#中,使用TcpClient進行SSL/TLS加密通信需要使用SslStream類
using System;
using System.IO;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Text;
namespace TcpClientSslDemo
{
class Program
{
static void Main(string[] args)
{
// 服務器地址和端口
string serverAddress = "example.com";
int serverPort = 443;
// 創建TcpClient實例
using (TcpClient client = new TcpClient(serverAddress, serverPort))
{
// 獲取網絡流
NetworkStream networkStream = client.GetStream();
// 創建SslStream實例
using (SslStream sslStream = new SslStream(networkStream, false, ValidateServerCertificate))
{
// 開始SSL/TLS握手
sslStream.AuthenticateAsClient(serverAddress, null, SslProtocols.Tls12, true);
// 發送數據
byte[] message = Encoding.UTF8.GetBytes("GET / HTTP/1.1\r\nHost: example.com\r\nConnection: close\r\n\r\n");
sslStream.Write(message);
// 接收數據
byte[] buffer = new byte[2048];
int bytesRead = sslStream.Read(buffer, 0, buffer.Length);
// 處理接收到的數據
string response = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Console.WriteLine(response);
}
}
}
// 驗證服務器證書的回調函數
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
if (sslPolicyErrors == SslPolicyErrors.None)
return true;
Console.WriteLine("Certificate error: {0}", sslPolicyErrors);
return false;
}
}
}
這個示例展示了如何使用TcpClient和SslStream類創建一個簡單的客戶端,連接到服務器并進行SSL/TLS加密通信。請注意,這個示例僅用于演示目的,實際應用中可能需要根據具體需求進行修改。