原文網址: http://www.cnblogs.com/csdev
Networkcomms 是一款C# 語言編寫的TCP/UDP通信框架 作者是英國人 以前是收費的 目前作者已經開源 許可是:Apache License v2
開源地址是:https://github.com/MarcFletcher/NetworkComms.Net
首先對證書這一塊,本人也不是特別了解,只是把NetworkComms本身帶的Demo重新進行了整理。如果寫的不對,請批評指正。
首先
服務器端:
(1)生成證書:
public void CreateCert() { if (!File.Exists("testCertificate.pfx")) { CertificateDetails details = new CertificateDetails("CN=wwww", DateTime.Now, DateTime.Now.AddYears(1)); SSLTools.CreateSelfSignedCertificatePFX(details, "testCertificate.pfx"); } X509Certificate cert = new X509Certificate2("testCertificate.pfx"); sslOptions = new SSLOptions(cert, true); }
我們看到上面的代碼中 證書作為參數賦值給 sslOptions
sslOptions將會賦值給監聽器,代碼如下:
ConnectionListenerBase listener = new TCPConnectionListener(customOptions, ApplicationLayerProtocolStatus.Enabled,sslOptions); Connection.StartListening(listener, thePoint, true);
運行服務器端,會生成一個
testCertificate.pfx文件,我們需要把這個文件拷貝給客戶端
客戶端相關代碼:
X509Certificate cert = new X509Certificate2("testCertificate.pfx"); SSLOptions sslOptions = new SSLOptions(cert, true); connInfo = new ConnectionInfo(txtIP.Text, int.Parse(txtPort.Text)); newTcpConnection = TCPConnection.GetConnection(connInfo, customOptions, sslOptions); button1.Enabled = false; button1.Text = "連接成功";
這樣沒有證書的客戶端就無法同服務器端建立連接了
源碼:http://pan.baidu.com/s/1dEJEdNz