![](/img/trans.png)
[英]SslStream.AuthenticateAsClient - A non-blocking socket operation could not be completed immediately on send
[英]How to Create SslStream for a non-blocking async socket
我有一個多線程異步System.Net.Socket
偵聽端口。 如果我從HTTP獲得請求,我沒有任何問題,但最近我不得不為我的應用程序添加https支持。
客戶端給了我一個.arm
認證文件。 它中包含base-64編碼的ASCII數據。 文件名是cert.arm
,它存儲在我的解決方案文件夾的根目錄中。
以下是我到目前為止使用該證書所做的事情:
using System;
using System.Net;
using System.Threading;
using System.Net.Security;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
namespace SocketExample
{
public class StackOverFlow
{
public static ManualResetEvent _manualResetEvent = new ManualResetEvent(false);
private static X509Certificate2 _cert = X509Certificate2("..\\..\\cert.arm");
static void Main(string[] args)
{
StartListening();
}
private static void StartListening()
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Any, 9002);
if (localEndPoint != null)
{
Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
if (listener != null)
{
listener.Bind(localEndPoint);
listener.Listen(10);
Console.WriteLine("Socket listener is running...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
}
}
private static void AcceptCallback(IAsyncResult ar)
{
_manualResetEvent.Set();
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
SslStream sslStream = new SslStream(new NetworkStream(handler, false));
sslStream.AuthenticateAsServer(_cert); // I get exception on this line
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
}
private static void ReceiveCallback(IAsyncResult result)
{
StateObject state = (StateObject)result.AsyncState;
Socket handler = state.workSocket;
int numBytesReceived = handler.EndReceive(result);
if (!handler.Connected)
{
handler.Close();
return;
}
if (numBytesReceived > 0)
{
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, numBytesReceived));
string[] lines = state.sb.ToString().Split('\n');
if (lines[lines.Length - 1] == "EOF")
{
// All Data Received. Do Something.
}
else
{
// All Data is not received. Continue reading...
handler.BeginReceive(state.buffer, 0, state.buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
}
}
}
}
}
認證文件已成功創建。 我可以在_cert變量中看到數據。 沒關系。
問題是,當我調用AuthenticateAsServer
方法時,我得到NotSupportedException
,它說:“服務器模式SSL必須使用帶有相關私鑰的證書”。
如何將此認證文件應用於我的套接字?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.